CSS Transitions: Border Slides Instead of Fading

20,866

Solution 1

If you want to animate the color, animate the color, not the entire border. You're now also animating it from 0 pixels to 3 pixels, so of course it slides in. You should just give it a default transparent border instead.

div {
    line-height: 50px;
    width: 100px;
    text-align: center;
    cursor: pointer;
    transition: border-color .5s ease-in-out;
    border-top: 3px solid transparent;
}

div:hover {
    border-top-color: #000;
}

Sample on JSfiddle

As a sidenote: -moz-transition is obsolete nowadays, since FF17 or so Mozilla supports the CSS Transitions module without prefix.

Update dec 2014: as I noticed this answer is still being viewed and upvoted frequently, please note that transition is no longer prefixed in any current or recently superseded browsers.

Solution 2

In this case - you are going to need to have a border to begin with as well. Make it transparent in the first state. This way it will not "grow" into place... and the color will just fade as it changes.

http://jsfiddle.net/kLnQL/11/

div {
  border: 3px solid transparent;
}

div:hover {
  border: 3px solid #f06;
}
Share:
20,866
Moussa Harajli
Author by

Moussa Harajli

Updated on July 05, 2022

Comments

  • Moussa Harajli
    Moussa Harajli almost 2 years

    I styled a link so that when you hover it, there will appear a border on the top; and when you hover off the border will disappear with a transition. The border slides in instead of fading in when you hover over it and off. I want the border to fade in instead of slide. How can I do this? Here is a JsFiddle

    HTML

    <div>Text</div>
    

    CSS

    div {
        line-height: 50px;
        width: 100px;
        text-align: center;
        cursor: pointer;
        transition: border .2s ease-in-out;
        -webkit-transition: border .2s ease-in-out;
        -moz-transition: border .2s ease-in-out;
    }
    
    div:hover {
        border-top: 3px solid #000;
    }
    
    html, body {
        margin: 0;
        padding: 0;
    }