cup_of cup_of - 2 months ago 6
CSS Question

Prevent psuedo element pushing content down

Hello I have a box that has some content in it. I set up a psuedo

:before
element to show on hover. This psuedo element is an image that covers the entire box set as a background image. It works, but it pushes the content in the box down below the box. I would like it so the content remains in place on hover and the content appears over the psuedo element.

HTML:

<div class="box">
<p>content content content</p>
</div>


CSS:

.box {
width: 200px;
height: 200px;
background-color: #333;
}

.box p {
color: green;
}

.box:before {
content: '';
background: url('https://ewans.files.wordpress.com/2008/07/grey1.jpg');
width: 200px;
height: 200px;
}

.box:hover:before {
display: block;
}


Here is the jsfiddle link

jsfiddle

Is there any way to have this psuedo background image to not push the content down? I would like the content to stay in the same place on top of the psuedo element. (Content not being covered by the psuedo element)

Also you may be asking why not just change the background color of the box on hover. This is because the background image is a custom image, I just used that grey image as an example.

Thanks

Answer

Do like this, where you position the pseudo absolute.

.box {
  position: relative;
   width: 200px;
   height: 200px;
   background-color: #333;
}

.box p {
  color: green;
  position: relative;
  z-index: 2;
}

.box:before {
  content: '';
  display: none;
  position: absolute;
  background: url('https://ewans.files.wordpress.com/2008/07/grey1.jpg');
  top: 0;
  left: 0;
  width: 200px;
  height: 200px;
}

.box:hover:before {
  display: block;
}
<div class="box">
    <p>content content content</p>
</div>