Darken background when opening modal window/div

Asked

Viewed 6,060 times

2

I tried to create something like modal, thus:

.try-modal{ 
    position: absolute;
    top:35%;
    left:25%;
    right: 25%;
    width: 50%;
    height: 400px;
    background-color: white;
    z-index: 2;
}

I call to <div class="try-modal"> with Jquery, So far so good. But now I wanted the back, after appearing this "modal", what was in the background was half dark as if it were the modal of the bootstrap. Is there a code or Tricks to do this?

1 answer

5


Considering that all the functionality is ok (as you stated in the question), just make it add a 2nd element, done this, control the display with the z-index.

Example:

.try-modal-overlay {
    position: fixed;
    top: 0; right: 0; bottom: 0; left: 0;
    background: rgba(#000, .4);
    z-index: 2;
}
.try-modal{
    position: absolute;
    top:35%;
    left:25%;
    right: 25%;
    width: 50%;
    height: 400px;
    background-color: white;
    z-index: 3; 
}

Thus the element try-modal-overlay will be behind your modal and with transparent black background.


An alternative would be to use the element :before in his css, eliminating the need to add another element with jQuery.

.try-modal:before {
    content: '';
    position: fixed;
    top: 0; right: 0; bottom: 0; left: 0;
    background: rgba(#000, .4);
    z-index: 2;
}
.try-modal {
    ...[demais estilos]...
    z-index: 3; //Não esqueça de alterar esse index também
}

I particularly prefer the first option because it is more segmented, but it is up to you.

  • So basically just create another layer

  • 1

    @2016 programmerisso. You can use another CSS technique, using before, I will update the answer.

  • 1

    Thank you @Celsomtrindade

Browser other questions tagged

You are not signed in. Login or sign up in order to post.