这并不完美,但到目前为止我想出的最佳解决方案是使用 :after 伪元素对其进行屏蔽。这样就不需要在整个文本中添加额外的元素。
例如:
h1 {
/* A nice big spacing so you can see the effect */
letter-spacing: 1em;
/* we need relative positioning here so our pseudo element stays within h1's box */
position: relative;
/* centring text throws up another issue, which we'll address in a moment */
text-align: center;
/* the underline */
text-decoration: underline;
}
h1:after {
/* absolute positioning keeps it within h1's relative positioned box, takes it out of the document flow and forces a block-style display */
position: absolute;
/* the same width as our letter-spacing property on the h1 element */
width: 1em;
/* we need to make sure our 'mask' is tall enough to hide the underline. For my own purpose 200% was enough, but you can play and see what suits you */
height: 200%;
/* set the background colour to the same as whatever the background colour is behind your element. I've used a red box here so you can see it on your page before you change the colour ;) */
background-color: #990000;
/* give the browser some text to render (if you're familiar with clearing floats like this, you should understand why this is important) */
content: ".";
/* hide the dynamic text you've just added off the screen somewhere */
text-indent: -9999em;
/* this is the magic part - pull the mask off the left and hide the underline beneath */
margin-left: -1em;
}
<h1>My letter-spaced, underlined element!</h1>
就是这样!
如果您想更好地控制颜色、位置等,您也可以使用边框,但除非您有固定宽度,否则这些都需要您添加 span 元素。
例如,我目前正在开发一个网站,该网站要求 h3 元素具有 2 像素的字母间距、居中的文本和下划线,并在文本和下划线之间添加空间。我的css如下:
h3.location {
letter-spacing: 2px;
position: relative;
text-align: center;
font-variant: small-caps;
font-weight: normal;
margin-top: 50px;
}
h3.location span {
padding-bottom: 2px;
border-bottom: 1px #000000 solid;
}
h3.location:after {
position: absolute;
width: 2px;
height: 200%;
background-color: #f2f2f2;
content: ".";
text-indent: -9999em;
margin-left: -2px;
}
我的 HTML 是:
<h3><span>Heading</span></h3>
注意事项:
这不是 100% 漂亮的 CSS,但它至少意味着您不必修改和修改 HTML 即可获得相同的结果。
我还没有在带有背景图像的元素上尝试这个,所以还没有想到实现这个的方法。
居中文本使浏览器将文本显示在错误的位置(它占文本 + 之后的额外间距),因此所有内容都向左拉。直接在 h1 元素(不是 :after 伪元素)上添加文本缩进 0.5em(我们在顶部示例中使用的 1em 字母间距的一半)应该解决这个问题,尽管我没有测试这还没有。
非常感谢收到任何反馈!
尼尔