有没有办法控制文本装饰中下划线的位置:下划线?
<a href="#">Example link</a>
上面的例子默认有一个下划线......有没有办法将下划线向下微调几个像素,以便在文本和下划线之间有更多空间?
唯一的方法是使用边框而不是下划线。下划线是出了名的不灵活。
a {
border-bottom: 1px solid currentColor; /* Or whatever color you want */
text-decoration: none;
}
这是一个演示。如果空间不够,您可以轻松添加更多空间——如果空间太多,那就不太方便了。
CSS
p {
line-height: 1.6;
}
.underline {
text-decoration: none;
position: relative;
}
.underline:after {
position: absolute;
height: 1px;
margin: 0 auto;
content: '';
left: 0;
right: 0;
width: 90%;
color: #000;
background-color: red;
left: 0;
bottom: -3px; /* adjust this to move up and down. you may have to adjust the line height of the paragraph if you move it down a lot. */
}
HTML
<p>This is some example text. From this page, you can <a href="#">read more example text</a>, or you can <a href="#" class="underline">visit the bookshop</a> to read example text later.</p>
这是一个更高级的演示,附有我制作的屏幕截图,在 悬停时为下划线设置动画,更改颜色等...
CSS 3 中有建议的text-underline-position
属性,但似乎还没有在任何浏览器中实现。
因此,如其他答案中所建议的,您需要使用抑制下划线并添加底部边框的解决方法。
请注意,下划线不会添加到元素的总高度,但底部边框会。在某些情况下,您可能希望使用outline-bottom
- 它不会增加总高度 - 代替(尽管它不像 那样被广泛支持border-bottom
)。
CSS 文本装饰模块 4 级中有一个text-underline-offset
属性,允许您将装饰从其原始位置移动指定距离。
截至 2020 年初,仅 Safari 12.1+ 和 Firefox 70+ 支持此功能。
text-underline-offset
属性接受这些值:
auto
- 默认,使浏览器选择适当的偏移量。from-font
- 如果使用的字体指定了首选偏移量,则使用该偏移量,否则将回退到auto
.<length>
- 以“通常”的 CSS 长度单位指定距离。用于em
允许按比例缩放font-size
。下面的例子:
p {
text-decoration: underline;
text-decoration-color: red;
margin-bottom: 1.5em;
}
p.test {
position: relative;
}
p.test::after {
position: absolute;
content: '';
display: block;
height: 1px;
width: 100%;
background: blue;
bottom: 0;
}
<p style="text-underline-offset: 0.75em;" class="test">
If you see our red underline <strong>below</strong> the blue line, this property works in your browser.
</p>
<p style="text-underline-offset: auto">
And now let’s try it with `text-underline-offset` set to `auto`.
</p>
<p style="text-underline-offset: from-font">
With `text-underline-offset` set to `from-font`, it probably looks the same as above.
</p>
您可以使用text-underline-position: under;
<body>
<h1>
<a href="#"
style="text-decoration: underline; text-underline-position: under;" >
My link</a>
</h1>
</body>
有关更多详细信息,请查看https://developer.mozilla.org/en-US/docs/Web/CSS/text-underline-position
使用边框底部而不是下划线
a{
border-bottom: 1px solid #000;
padding-bottom: 2px;
}
更改 padding-bottom 以调整空间
有一个属性text-underline-position: under
。但仅在 Chrome 和 IE 10+ 中受支持。
更多信息:https ://css-tricks.com/almanac/properties/t/text-underline-position/ https://developer.mozilla.org/en-US/docs/Web/CSS/text-underline-position
默认情况下,使用border-bottom-width
andborder-bottom-style
将使边框与文本颜色相同:
text-decoration: none;
border-bottom-width: 1px;
border-bottom-style: solid;
padding-bottom: 1px;
我会改用边框。更容易控制。