Moussa Harajli
Moussa Harajli

Reputation: 1516

CSS Transitions: Border Slides Instead of Fading

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;
}

Upvotes: 6

Views: 21298

Answers (2)

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

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.

Upvotes: 20

nouveau
nouveau

Reputation: 1262

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;
}

Upvotes: 2

Related Questions