我试图在我的每个 h2 标签后划一行。我无法弄清楚我应该如何分辨宽度,因为 h2 标题的长度从 h2 到 h2 是不同的。
我使用 :after 方法来创建行
h2:after {
position: absolute;
content: "";
height: 2px;
background-color: #242424;
width: 50%;
margin-left: 15px;
top: 50%;
}
在这里检查代码:http://jsfiddle.net/s9gHf/ 如您所见,线条变得太宽,使网站变得太宽。
最佳答案
您可以通过额外的 <span>
来实现此目的:
h2 {
font-size: 1rem;
position: relative;
}
h2 span {
background-color: white;
padding-right: 10px;
}
h2:after {
content: "";
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 0.5em;
border-top: 1px solid black;
z-index: -1;
}
<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>
另一种没有额外的解决方案 <span>
但需要 overflow: hidden
在 <h2>
上:
h2 {
font-size: 1rem;
overflow: hidden;
}
h2:after {
content: "";
display: inline-block;
height: 0.5em;
vertical-align: bottom;
width: 100%;
margin-right: -100%;
margin-left: 10px;
border-top: 1px solid black;
}
<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>
关于css - 使用 css 在文本后创建行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20935191/