Animate the CSS transition property within :after/:before pseudo-classes

久未见 提交于 2019-11-29 23:56:25
Litek

Your fiddle does work for me in Firefox. And as far as I know, and if this article is up to date this is the only browser that can animate pseudo-elements.


EDIT: As of 2016, the link to article is broken and the relevant WebKit bug was fixed 4 years ago. Read on to see other answers, this one is obsolete.

Google Chrome added the webkit bug fix to Version 27.0.1453.110 m

This WebKit bug was fixed: http://trac.webkit.org/changeset/138632

IT IS POSSIBLE to animate pseudo :before and :after, here are a couple of examples for animating the psuedo-elements :before and :after.

Here is a modification of your example above with some edits, that make it animate in and out more smoothly without the simulated mouseleave / mouseout delay on hover:

http://jsfiddle.net/MxTvw/234/

Try adding the main selector #foo with the grouped :hover pseudo-class in your second :hover pseudo-class rule. Also add the transition property, and not just the vendor specific prefixed properties for transition:

#foo:after{
   display: block;
   content: '';
   width: 200px;
   height: 200px;
   background: red;
   -webkit-transition: all .4s ease-in-out;
   -moz-transition: all .4s ease-in-out;
   -o-transition: all .4s ease-in-out;
   transition: all .4s ease-in-out;
} 

#foo,
#foo:hover:after,
#foo:hover:before{
   width: 250px;
   height: 250px;
}

Note that going forward any Pseudo Elements like :before and :after should use the double colon syntax ::before and ::after. This example simulates a fade in and out using a overlay background-color and a background-image on hover:

http://jsfiddle.net/MxTvw/233/

This example simulates a animate of rotation on hover:

http://jsfiddle.net/Jm54S/28/

Of course moving forward with css3 standards we could use ::before and ::after.

This works in latest Firefox, Chrome, Safari, Opera 18+, IE10, IE11 (IE9 and below do not support css3 transitions or animate.)

It does not seem to work now, however according to the W3 specs you can apply transitions to pseudo-elements. Maybe some time in future…

I just found out that you can animate :after and :before (:

Code example-

  .model-item {
    position: relative;

    &:after {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      right: 0;
      background: transparent;
      transition: all .3s;
    }
  }

  .opc {
    &:after {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      right: 0;
      background: rgba(0, 51, 92, .75);
    }
  }

I have the div .model-item and i needed to animate his :after. So i've added another class which changes background and i added the transition code to the main :after (before animation)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!