2017-10-10 77 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; 
     } 
    }