Search code examples
cssopacityfade

CSS3 hover opacity ease-in-out effect?


Is there any better and simpler way writing opacity ease-in-out effect below?

CSS:

 .button-hover {
    font-family: arial black;
    font-size: 100px;
    color: #000;

    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -ms-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
    opacity: 1;
}

.button-hover:hover {
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -ms-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
    opacity: 0.5;
}

As you can see that I repeat these lines twice which does not seem ideal:

    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -ms-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;

HTML:

<div class="container">
    <a href="#" class="button-hover">HOVER ME</a>
</div>

jsfiddle


Solution

  • Don't repeat the transition rules. CSS pre-processors can help with the vendor prefixing but you really don't need to (and shouldn't) repeat the transition declarations in the :hover. Just set them once in elements's default state like so:

    .button-hover {
        font-family: arial black;
        font-size: 100px;
        color: #000;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
        opacity: 1;
    }
    
    .button-hover:hover {
        opacity: 0.5;
    }
    <div class="container">
        <a href="#" class="button-hover">HOVER ME</a>
    </div>

    Understanding CSS3 Transitions