Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Overlay with pseudo element

Tags:

html

css

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.

like image 222
Jason DeClau Avatar asked Jan 03 '16 20:01

Jason DeClau


2 Answers

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>
like image 124
Josh Crozier Avatar answered Sep 30 '22 12:09

Josh Crozier


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 ^^

like image 37
dragoweb Avatar answered Sep 30 '22 14:09

dragoweb