我正试图在网站的头条新闻下创建一个小边框。我在伪元素之前和之后使用它。代码有点特别,因为我正在调整我使用的模板的代码。就像这个see fiddle
问题是"左:48%;" property:我手动设置了它,但是根据屏幕的大小,它可能是居中的,所以它没有响应。有没有办法让边框始终位于文本的中心?
.headline p:before,
.headline p:after {
position: absolute;
left: 48%;
display: block;
width: 70px;
border-bottom: 3px solid black;
content: "";
}
h3 {
text-align: center;
}

<div class="headline">
<h3>
My title
</h3>
<p>
</p>
</div>
&#13;
答案 0 :(得分:3)
使用calc()
css函数如下:
.headline p:before,
.headline p:after {
position: absolute;
left: calc(50% - 35px);
display: block;
width: 70px;
border-bottom: 3px solid black;
content: "";
}
h3 {
text-align: center;
}
&#13;
<div class="headline">
<h3>My title</h3>
<p></p>
</div>
&#13;
答案 1 :(得分:1)
将伪元素设为left
和right
属性 - 然后使用margin: auto
居中。
.headline p:before,
.headline p:after {
position: absolute;
left: 0;
right: 0;
margin: auto;
display: block;
width: 70px;
border-bottom: 3px solid black;
content: "";
}
h3 {
text-align: center;
}
<div class="headline">
<h3>
My title
</h3>
<p>
</p>
</div>
答案 2 :(得分:1)
使用保证金属性
将代码重写为
.headline p:before, .headline p:after {
margin: 0 auto;
width: 70px;
border-bottom: 3px solid black;
content: "";
}
.headline p:before,
.headline p:after {
margin: 0 auto;
display: block;
width: 70px;
border-bottom: 3px solid black;
content: "";
}
h3 {
text-align: center;
}
&#13;
<div class="headline">
<h3>
My title
</h3>
<p>
</p>
</div>
&#13;
答案 3 :(得分:1)
只需使用保证金:自动
.headline p:before,
.headline p:after {
margin: auto;
display: block;
width: 70px;
border-bottom: 1px solid black;
content: "";
}
h3 {
text-align: center;
}
<div class="headline">
<h3>
My title
</h3>
<p>
</p>
</div>