2017-10-10 75 views
3

我有一個包含僞元素來控制下劃線的文本元素。我想要達到的是元素到達兩行(或更多)時,我希望下劃線爲元素的100%寬度,但現在它僅佔最後一行的100%(請參見截圖)。CSS:多行上的僞邊界寬度

enter image description here

我已經提出了一個小提琴向你展示我的意思:https://jsfiddle.net/m6rmxuoy/1/

有兩個例子:一個display: inlineh2元素:

.wrapper { 
    width: 260px; 

    h2 { 
    position: relative; 
    display: inline; 

    background-color: yellow; 

    &:after { 
     position: absolute; 
     left: 0; 
     bottom: 0; 
     width: 80px; 
     height: 3px; 

     background-color: #0077bc; 
     content: ''; 
    } 

    &:hover:after { 
     width: 100%; 
    } 
    } 
} 

問題這是懸停狀態下行的寬度不會填滿第一行的寬度。

的第二次嘗試,與display: inline-block,適應了包裝寬度,而不是在線路最長停止,因爲display: inline做:

.wrapper2 { 
    width: 260px; 

    h2 { 
    position: relative; 
    display: inline-block; 

    background-color: yellow; 

    &:after { 
     position: absolute; 
     left: 0; 
     bottom: 0; 
     width: 80px; 
     height: 3px; 

     background-color: #0077bc; 
     content: ''; 
    } 

    &:hover:after { 
     width: 100%; 
    } 
    } 
} 

我想達到的結果是這樣的:

Hope to achieve this

我已經搜索了相當一段時間了,甚至發現了box-decoration-break: clone;,但它並沒有幫助我使用僞元素。

任何想法?

+0

是的......你不能這麼做......這不是線框模型的工作方式。 - https://stackoverflow.com/questions/37406353/make-container-shrink-to-fit-child-elements-as-they-wrap –

+0

爲什麼不把它換成帶底部邊框的內嵌塊div? – abimelex

回答

1

這對於CSS來說是不可能的,這與瀏覽器如何呈現CSS相反。我能得到的最接近的解決方案是在文本添加換行符爲wrapper2(在inline-block例子):

This text has too many<br>characters for 1 line

這是不理想,但更動態的解決方案需要的JavaScript,如提供了一個在這裏:Shrink DIV to text that's wrapped to its max-width?

-1

我想請從H2標籤顯示屬性將解決這個問題,如果我有明白你的問題。

p { 
     font-size: 18px; 
     font-weight: normal; 
     color: #fff; 
     margin: 12px 0 0; 
     position: relative; 
     &:before { 
      position: absolute; 
      width: 100%; 
      height: 2px; 
      background: blue; 
      content: ''; 
      display: none; 
      bottom: 0; 
     } 
     &:hover:before { 
      display: block; 
     } 
    }