Search code examples
csscss-transitionsfade

Is possible use fade transition on tag 'content' only with css?


Please view this code jsfiddle: http://jsfiddle.net/rflfn/6wCp6/

<div id="menu">
    <ul>
        <li><a href="#">Link #1</a></li>
        <li><a href="#">Link #2</a></li>
        <li><a href="#">Link #3</a></li>
        <li><a href="#">Link #4</a></li>
    </ul>
</div>

CSS:

*{
    margin: 0;
    padding: 0;
    text-decoration: none;
    font-family: arial;
    font-size: 16px;
}
a{
    color: #000000;
}
a:hover{
    color: #860000;    
}
#menu{
    margin: 15px auto;
    padding: 20px;
    width: 300px;
    background: #DDDDDD;

    border-radius: 5px;
    box-shadow: 0 0 5px #000000;
}
#menu ul{
    list-style: none;
}
#menu li:before{
    margin-right: 10px;
    content: url("http://st.deviantart.net/emoticons/s/smile.gif");

    transition: all 0.5s ease 0s;
    /* transition: content 0.5s ease 0s; */
}
#menu li:hover:before{
    content: url("http://st.deviantart.net/emoticons/r/razz.gif");
}

I have one image on tag 'li' and other image on 'li:hover', is possible make transition with fade only using css?


Solution

  • You can do this by using both pseudo elements :before/after and using the CSS3 transition to animate the opacity of both on hover. This will create a fade transition between both images.

    DEMO

    CSS :

    *{
        margin: 0;
        padding: 0;
        text-decoration: none;
        font-family: arial;
        font-size: 16px;
    }
    a{
        color: #000000;
    }
    a:hover{
        color: #860000;    
    }
    #menu{
        margin: 15px auto;
        padding: 20px;
        width: 300px;
        background: #DDDDDD;
    
        border-radius: 5px;
        box-shadow: 0 0 5px #000000;
    }
    #menu ul{
        list-style: none;
    }
    #menu ul li{
        position:relative;
    }
    #menu li:before{
        margin-right: 10px;
        content: url("http://st.deviantart.net/emoticons/s/smile.gif");
    
        transition: opacity 0.5s ease;
        -webkit-transition: opacity 0.5s ease;
    }
    #menu li:after{
        content: url("http://st.deviantart.net/emoticons/r/razz.gif");
        position:absolute;
        left:0;
        opacity:0;
    
        transition: opacity 0.5s ease;
        -webkit-transition: opacity 0.5s ease;
    }
    #menu li:hover:after{
        opacity:1;
    }
    #menu li:hover:before{
        opacity:0;
    }
    

    EDIT :

    Even better, you can position both images one on top of the other and with z-index and css transition animate the opacity of ony one image :

    DEMO