Html CSS 过渡:边框滑动而不是褪色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16847647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:56:38  来源:igfitidea点击:

CSS Transitions: Border Slides Instead of Fading

htmlcsstransition

提问by Moussa Harajli

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

我设计了一个链接,这样当你悬停它时,顶部会出现一个边框;当您将鼠标悬停在边框上时,边框将随着过渡而消失。当您将鼠标悬停在边框上并关闭时,边框会滑入而不是淡入。我希望边框淡入而不是滑动。我怎样才能做到这一点?这是一个JsFiddle

HTML

HTML

<div>Text</div>

CSS

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

回答by Niels Keurentjes

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.

如果要为颜色设置动画,请为颜色设置动画,而不是整个边框。您现在也将其从 0 像素设置为 3 像素,因此它当然会滑入。您应该只给它一个默认的透明边框。

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

Sample on JSfiddle

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

作为旁注:-moz-transition现在已经过时了,因为 FF17 左右 Mozilla 支持没有前缀的 CSS Transitions 模块。

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

2014 年 12 月更新:因为我注意到这个答案仍然被经常查看和投票,请注意transition任何当前或最近被取代的浏览器中不再有前缀。

回答by nouveau

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/

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

div {
  border: 3px solid transparent;
}

div:hover {
  border: 3px solid #f06;
}