Using CSS transition on ::before pseudo element

Issue

.posts .img-hover:before {
  content: '';
  display: block;
  opacity: 0;
  -webkit-transition: opacity 1.2s ease;
  -moz-transition: opacity 1.2s ease;
  -ms-transition: opacity 1.2s ease;
  -o-transition: opacity 1.2s ease;
  transition: opacity 1.2s ease-out;
}
.posts .img-hover:hover:before {
  content: '';
  display: block;
  background: url("img/Texture1.png");
  width: 320px;
  /* image width */
  height: 220px;
  /* image height */
  position: absolute;
  top: 13px;
  right: 2px;
  opacity: 1;
}
<div class="posts">
  <a href="#">
    <h2 class="postname"> 
         Travel Flashback #1 </h2>
  </a>
  <a class="img-hover" href="#">
    <img width="960" height="720" src="http://.." class="img-hover" alt="" />
  </a>
</div>

I have one problem with this code. As you see I want transition over pseudo element ::before, which has bkg img.

When I hover on, transition works smoothly, but when I leave mouse, bkg img goes away immediately without transition.

Can you please suggest something?

Solution

On the hover you probably only want the css related to the transition, not the actual styles for the pseudo element. Try this

.posts .img-hover:before {
    content: '';
    display: block;
    background: url("img/Texture1.png");
    width: 320px; /* image width */
    height: 220px; /* image height */
    position: absolute;
    top: 13px;
    right: 2px;
    opacity: 0;
    -webkit-transition: opacity 1.2s ease;
    -moz-transition: opacity 1.2s ease;
    -ms-transition: opacity 1.2s ease;
    -o-transition: opacity 1.2s ease;
    transition:  opacity 1.2s ease-out;
}
.posts .img-hover:hover:before{
    opacity: 1;
}

Answered By – ynter

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published