【发布时间】:2013-03-07 07:04:42
【问题描述】:
我有一个链接<a class="link-articles" href="#articles">My Articles</a>
还有我的 CSS .link-articles { text-decoration: underline; color: blue; }
但是,在悬停时,我希望用红色下划线代替蓝色下划线,但文本应保持蓝色,只有下划线变为红色。
这样的事情怎么办?
【问题讨论】:
我有一个链接<a class="link-articles" href="#articles">My Articles</a>
还有我的 CSS .link-articles { text-decoration: underline; color: blue; }
但是,在悬停时,我希望用红色下划线代替蓝色下划线,但文本应保持蓝色,只有下划线变为红色。
这样的事情怎么办?
【问题讨论】:
只要做:
a:hover {
text-decoration-style: dotted
}
https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration-style
【讨论】:
.link-articles { text-decoration: none; border-bottom: 1px dotted blue; }
.link-articles:hover { text-decoration: none; border-bottom: 1px dotted red; }
【讨论】:
悬停时显示底部边框:
a.link-articles {
text-decoration: none;
border-bottom: 1px dotted blue;
}
a.link-articles:hover {
border-bottom: 1px dotted red;
}
【讨论】:
由于您无法将 哪种颜色 指定为文本下划线的第二种颜色,因此一种策略是删除它并使用边框。
.link-articles
{
border-bottom: solid 1px blue;
text-decoration: none;
}
.link-articles:hover
{
border-bottom-color: red;
}
请注意,如果您离开text-underline,它会在悬停时向下移动,因为它的位置与底部边框的位置并不完全相同。
这种方法还有一个额外的优势,即可以通过使用line-height 来定位下划线,并且可以通过将solid 替换为dotted 或dashed 来替代线条样式。 p>
无边界方法:
正如@Pacerier 在 cmets 中指出的那样,这是使用伪类和 CSS 内容 (JSFiddle) 的替代策略:
.link-articles
{
position: relative;
}
.link-articles[href="#articles"]:after
{
content: 'My Articles';
}
.link-articles:after
{
color: red;
left: 0;
position: absolute;
top: 0;
}
但是,使用抗锯齿功能时,文本边缘可能会有一些颜色混合。如果您不喜欢在 CSS 中手动输入 content,您可以使用属性或重复元素。
【讨论】:
line-height 和使用不同的边框样式(例如 dotted)来微调它的位置。
line-height如何精确控制线的位置?当我在 Safari 中测试时,行距文本的距离不受影响。比周围文本更大的行高只会增加下一行的空间。较小的行高根本没有影响。边框与文本的距离永远不会改变。也许它适用于其他浏览器,但它只适用于受控环境,如 Intranet。
line-height 属性与下划线无关。 padding-bottom 属性可以提供帮助,但我会从答案中删除该措辞,因此没有人会怀疑。感谢您向我指出这一点。
line-height 属性确实有效,但前提是链接的display 设置为inline-block。无论如何,这有点令人困惑,并且不会添加到 OP 的答案中,所以我现在将其省略。
您可以使用 CSS3 text-decoration-color 属性,但遗憾的是,任何主流浏览器都不支持 text-decoration-color 属性。
Firefox 支持另一种选择,-moz-text-decoration-color 属性。
参考:http://www.w3schools.com/cssref/css3_pr_text-decoration-color.asp
浏览器支持:http://caniuse.com/#search=text-decoration-color
JSFiddle(不适用于所有浏览器)
因此,最好的方法仍然是使用border-bottom css 属性作为技巧。
【讨论】:
使用边框:
.link-articles { text-decoration: none; border-bottom: blue 1px solid; }
.link-articles:hover { border-bottom: red 1px dotted; }
【讨论】:
试试这个:
.link-articles{ text-decoration: none; border-bottom:1px dotted; border-color:blue; }
.link-articles:hover{ border-color:red; }
【讨论】:
:hover 样式用于设置用户将鼠标悬停在元素上时的样式。
.link-articles { ... }
.link-articles:hover { ... }
您可以使用border-bottom 属性而不是text-decoration 进行点、虚线和宽度样式。
【讨论】:
使用border-bottom:
a:hover.link-articles {border-bottom: 1px dotted red; text-decoration: none;}
【讨论】: