2016-02-26 57 views
1

在文本底部添加小border的最佳方式是什麼?固定大小的邊框底部

border具有爲中心和最大20px,但文本可能會很長,甚至200px.

所以這是這樣的:

<h1>This text can be longer than the border</h1> 
<style> 
.h1 {border-bottom:8px solid #000;} 
</style> 

我應該添加一個divh1後,並設置最大尺寸是多少?

+0

文本將是一行或多行?如果多行應該只在最後一行之後出現邊界? – Harry

+0

不應該是多行,但它可能發生在移動視圖....所以最好考慮多行。是的,只有在最後一行 –

回答

4

可以使用僞元素::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>

3

使用線性漸變:

或者你也可以使用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>

+1

我投了你@哈利! – dippas

1

提高dippasanswer,你可以看到,當你使用更大的寬度,在after元素的邊界是innacurate。您可以通過使用calc(50% - 100px);而不是50%來防止此問題,而100pxafter元素寬度的一半。

.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>

+0

實際上,如果你使用過'translateX(-50%)''left:50%'就可以工作:)原因是因爲我們需要在X軸上向左移動元素的一半寬度。我在我的答案的原始版本中自己也犯了同樣的錯誤:D – Harry

+1

哦,是的,你是絕對正確的!感謝您的信息,非常感謝! :) –