Search code examples
cssz-indexcss-filters

CSS z-index property doesn't work


I'm trying to give an hover effect to a div (a background picture) with the "filter" property. But it has got an influence on another div (my text) which is supposed to be over. I applied the z-index property (without forgetting the position of my divs) but it doesn't work. You'll see, my text is blurring too and is not supposed to. Could you tell me please what's wrong with my code ?

Here is the codepen showing my problem : https://codepen.io/Gillian-D/pen/qmqEQy

HTML

<div class="container">
  <div class="row">
     <div class="col-sm-6 left_part-padding">
         <div class="left_part">
           <div class="left_part_content">
             Left part
          </div>
         </div>
     </div> 
</div>

CSS

.container {
  margin-right: auto;
  margin-left: auto;
}


.left_part {
  height: 40vh;
  position: relative;
  z-index: 0;
  background-image: url(img/book2.jpeg);
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  background-color: #000;
  box-shadow: 0 50px 60px 0 rgba(0,0,0,.35);
  border-radius: 10px;
}


.left_part:hover {
-webkit-filter: blur(5px);
filter: blur(5px);
-webkit-transition: .5s ease-in-out;
position: relative;
z-index:0;
}

.left_part_content:hover {
color: #fed136;
position: relative;
z-index: 2;
}

.left_part-padding, .right_part-padding, .bottom_part-padding {
padding-left: 10px;
padding-right: 10px;
}

.left_part_content {
  color: white;
  font-family: "Raleway", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-size: 1.2rem;
  font-weight: 400;
  letter-spacing: .300em;
  margin-right: -.300em;
  text-align: center;
  vertical-align: middle;
  line-height: 40vh;
  position: relative;
  z-index: 2;
}

Thanks a lot!


Solution

  • When you add an effect on an element, in most cases their children gets affected as well, so in this case, you could use a pseudo element for the background-image

    Updated codepen

    Changed CSS rules

    .left_part {
      height: 40vh;
      position: relative;
      background-color: #000;
      box-shadow: 0 50px 60px 0 rgba(0,0,0,.35);
      border-radius: 10px;
    }
    
    .left_part::before {
      content: '';
      position: absolute;
      top: 0; left: 0;
      width: 100%;
      height: 100%;
      background-image: url(http://lorempixel.com/500/200/nature/1/);
      background-position: center center;
      background-repeat: no-repeat;
      background-size: cover;
      background-color: #000;
      border-radius: 10px;
    }
    
    .left_part:hover::before {
      -webkit-filter: blur(5px);
      filter: blur(5px);
    }