Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS transition on ::before pseudo element

.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?

like image 262
Tigran Carahunge Kuchatyan Avatar asked Sep 14 '16 11:09

Tigran Carahunge Kuchatyan


People also ask

When would you use the :: before or :: after pseudo-element in your CSS?

Special welcome offer: get $100 of free credit. CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.

What property do you use in conjunction with the before pseudo-element to display content before an element?

The content CSS property is used in conjunction with these pseudo-elements, to insert the generated content.

What can you do with the before pseudo-element?

The ::before pseudo-element can be used to insert some content before the content of an element.


1 Answers

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;
}
like image 102
ynter Avatar answered Sep 28 '22 22:09

ynter