在文本底部添加小border
的最佳方式是什么?固定大小的边框底部
的border
具有为中心和最大20px
,但文本可能会很长,甚至200px.
所以这是这样的:
<h1>This text can be longer than the border</h1>
<style>
.h1 {border-bottom:8px solid #000;}
</style>
我应该添加一个div
我h1
后,并设置最大尺寸是多少?
在文本底部添加小border
的最佳方式是什么?固定大小的边框底部
的border
具有为中心和最大20px
,但文本可能会很长,甚至200px.
所以这是这样的:
<h1>This text can be longer than the border</h1>
<style>
.h1 {border-bottom:8px solid #000;}
</style>
我应该添加一个div
我h1
后,并设置最大尺寸是多少?
可以使用伪元素::after
和使用left:50%
/transform:translateX(-50%)
中间对齐无论对于背景width
h1 {
position: relative;
display:inline-block;
/* min-width:200px */
}
h1::after {
border-bottom: 1px solid red;
bottom: -10px;
content: "";
height: 1px;
position: absolute;
width: 20px;
left:50%;
transform: translateX(-50%);
}
<h1>This text can be longer than the border</h1>
使用线性渐变:
或者你也可以使用linear-gradient
背景我做到这一点法师。使用渐变的好处是它不需要任何额外的可用于其他目的的伪元素。边框的厚度基于Y轴上的background-size
,边框的宽度基于X轴上的大小。 background-position
属性用于居中边界。
缺点是与伪元素相比,linear-gradient
的浏览器支持相对较差。渐变仅在IE10 +中受支持。
h1 {
display: inline-block;
padding-bottom: 4px; /* to give some gap between text and border */
background: linear-gradient(to right, black, black);
background-repeat: no-repeat;
background-size: 20px 2px;
background-position: 50% 100%;
}
<h1>This text can be longer than the border</h1><br>
<h1>Some text with lesser length</h1><br>
<h1>Some text</h1>
使用伪元素:
您可以使用伪元素做到这一点。通过添加一个伪元素与20px width
,绝对定位我们将能够产生所需的效果。 left: 50%
,translateX(-50%)
用于定位伪元素在中心。伪元素的height
确定边框的厚度,而background
确定边框的颜色。
这个优点是浏览器支持,因为它应该在IE8 +中工作。
h1 {
position: relative;
display: inline-block;
padding-bottom: 4px; /* to give some gap between text and border */
}
h1:after {
position: absolute;
content: '';
left: 50%;
bottom: -2px;
width: 20px;
height: 2px;
background: black;
transform: translateX(-50%);
}
<h1>This text can be longer than the border</h1>
<br>
<h1>Some text with lesser length</h1>
<br>
<h1>Some text</h1>
我投了你@哈利! – dippas
提高dippas的answer,你可以看到,当你使用更大的宽度,在after
元素的边界是innacurate。您可以通过使用calc(50% - 100px);
而不是50%来防止此问题,而100px
是after
元素宽度的一半。
.bottom-border {
position: relative;
display:inline-block;
}
.bottom-border::after {
border-bottom: 2px solid red;
bottom: -10px;
content: "";
height: 1px;
position: absolute;
width: 200px;
left: calc(50% - 100px);
transform: translateY(-50%);
}
<p class="bottom-border">
Hi, i am a quite long text, might be 200px, probably more i guess, but nobody knows really.
</p>
实际上,如果你使用过'translateX(-50%)''left:50%'就可以工作:)原因是因为我们需要在X轴上向左移动元素的一半宽度。我在我的答案的原始版本中自己也犯了同样的错误:D – Harry
哦,是的,你是绝对正确的!感谢您的信息,非常感谢! :) –
文本将是一行或多行?如果多行应该只在最后一行之后出现边界? – Harry
不应该是多行,但它可能发生在移动视图....所以最好考虑多行。是的,只有在最后一行 –