CSS (transition) after a pseudo element - how to transition content that shows on hover

user1680771 picture user1680771 · Oct 25, 2013 · Viewed 55.4k times · Source
<!DOCTYPE html>
<html>
<head>
<style> 

div
{
transition:after 3s;
-webkit-transition:after 3s;
}

div:hover:after
{
content:"- positive!";
}
</style>
</head>
<body>

<div>Test</div>

</body>
</html>

I have this sample code above. I'm trying to use 'transition' so that the text: '- positive!' takes 3 seconds to slide/show up. But it isn't working.. How to fix it?

Answer

3dgoo picture 3dgoo · Oct 25, 2013

after is not a valid value of transition.

Instead put transition as a property of the :after selector.

HTML

<div>Test</div>

CSS

div:after {
    content:" - positive!";
    position: relative;
    opacity: 0;
    top: -20px;
    -webkit-transition: all 3s;
    transition: all 3s;
}
div:hover:after {
    opacity: 1;
    top: 0px;
}

Demo

You can also have a different transition on the hover in and hover out state. This allows us to have a delay to show the pseudo-element but no delay to hide it.

CSS

div:after {
    content:" - positive!";
    position: relative;
    opacity: 0;
    top: -20px;
    -webkit-transition: all 250ms;
    transition: all 250ms;
}
div:hover:after {
    opacity: 1;
    top: 0px;
    -webkit-transition: all 3s;
    transition: all 3s;
}

Demo

Here is a list of browsers that support transitions on pseudo elements: http://css-tricks.com/transitions-and-animations-on-css-generated-content/