Jason DeClau
Jason DeClau

Reputation: 79

CSS Overlay with pseudo element

How do I create a CSS overlay with an pseudo element?

.modal {
     position:fixed;
     top:100px;
     margin-left: auto;
     margin-right: auto;
     left:0;
     right:0;
     width:500px;
     display:none;
     border:2px solid #736D61;
     background:#fff;
     padding:10px;
}
.modal:after {
     position:fixed;
     top:0px;
     left:0px;
     width:100%;
     height:100%;
     background:rgba(0,0,0,0.5);
}

I have tried this but it's not working.

Upvotes: 6

Views: 4565

Answers (2)

dragoweb
dragoweb

Reputation: 731

Another solution would be to use border-box. No pseud-classes needed :

.modal {
  background-color: #fff;
  left: 50%;
  border-radius: 6px;
  box-shadow: 0 0 0 9999px rgba(0,0,0,0.6);
  padding: 20px;
  position: fixed;
  top: 50%;
  transform: translate(-50%, -50%);  
  z-index: 999;   
}

Codepen example

It works also with outline :

outline: 9999px solid rgba(0,0,0,0.6);

Quick and easy ^^

Upvotes: 3

Josh Crozier
Josh Crozier

Reputation: 241078

It probably isn't working because the pseudo-element isn't generated if the content value is omitted. The default content value is none, which is likely why you aren't seeing the pseudo element. Therefore you need to specify a value other than none for the content property:

.modal:after {
  content: '';
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

It's also worth mentioning that since a pseudo element is essentially added as a child element, it will be positioned above the .modal element since a stacking context is established. To work around that, you could add a :before pseudo element to the .modal element's parent like this:

.modal {
  position: fixed;
  top: 100px;
  margin-left: auto;
  margin-right: auto;
  left: 0;
  right: 0;
  width: 500px;
  border: 2px solid #736D61;
  background: #fff;
  padding: 10px;
}

.modal-overlay:before {
  content: '';
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}
<div class="modal-overlay">
  <div class="modal">MODAL</div>
</div>

Upvotes: 5

Related Questions