2017-10-10 11 views
3

下線を制御する疑似要素を含むテキストの要素があります。私が達成したいのは、要素が2行(またはそれ以上)に達したとき、下線を要素の100%の幅にしたい場合ですが、最後の行の100%にしかなりません(スクリーンショット参照)。 h2要素のdisplay: inlineとの1:CSS:複数行の疑似ボーダー幅

.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%; 
    } 
    } 
} 

問題https://jsfiddle.net/m6rmxuoy/1/

は二つの例があります。

enter image description here

は、私が何を意味するかをお見せするためにバイオリンを設置しましたこれは、ホバー状態の行の幅が最初の行の幅までいっぱいにならないということです。

display: inline-blockと2回目の試行、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をどのようにレンダリングするかとは対照的です。私は得ることができる最も近いソリューションはwrapper2inline-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; 
     } 
    }