Search code examples
htmlcssz-indexbox-shadow

Weird CSS effect with box shadows - how to solve?


See this example:

enter image description here

I have several boxes with white background and huge black, translucent box shadows that overlap the boxes above. However, this leads to an irritating behavior: While the white background gets darker through the overlapping box shadows, nested objects, like text or other boxes, don't!

Could anybody tell me why this occurs? I guess it has something to do with z-index. I would like prevent this - the nested objects should become darker as well. Any solutions?

Thanks in advance!


Here's the code: https://jsfiddle.net/xq20hvp4/3/

<div>Coloured text <span>Box with background</span></div>
<div>Coloured text <span>Box with background</span></div>
<div>Coloured text <span>Box with background</span></div>
<div>Coloured text <span>Box with background</span></div>
<div>Coloured text <span>Box with background</span></div>

CSS:

div {
    margin: 20px;
    box-shadow: 0 0 0 250px rgba(0, 0, 0, 0.3);
    font-size: 25px;
    color: red;
    font-weight: bold;
    font-family: Consolas, Arial, sans-serif;
    background-color: #ffffff;
}
div span {
    background-color: #e7e7e7;
    color: #555555;
    font-weight: normal;
    font-size: 17px;
    padding: 1px 5px;
}

Solution

  • It's because those elements are on top of the div with the shadow. In order to put them behind, you can use position: relative; on the background element and give it z-index: 1:

    div {
      margin: 20px;
      box-shadow: 0 0 0 250px rgba(0, 0, 0, 0.3);
      font-size: 25px;
      color: red;
      font-weight: bold;
      font-family: Consolas, Arial, sans-serif;
      background-color: #ffffff;
    
      /* Add this */
      position: relative;
      z-index: 1;
    }
    
    div .box {
      background-color: #e7e7e7;
      color: #555555;
      font-weight: normal;
      font-size: 17px;
      padding: 1px 5px;
    }
    

    Here's an updated fiddle: https://jsfiddle.net/6wwz8usw/.