【问题标题】:Using the last line of an inline element as the width for :after pseudo element使用内联元素的最后一行作为 :after 伪元素的宽度
【发布时间】:2015-12-06 17:24:30
【问题描述】:

我正面临一个我正在努力克服的问题。

我猜想用一个例子来最好地证明这一点:

小提琴: http://jsfiddle.net/wchv2hmn/3/

在浏览器中:

div {
    background-color: blue;
    text-align: center;
}
span {
    position: relative;
    background-color: green;
    
}
span:after {
    content: '';
    display: block;
    position: absolute;
    left: 0;
    right: 0;
    height: 10px;
    width: 100%;
    background-color: red;
}
<div>
    <span>
        htejuteujetjtjehrehreheherhrehrehre sghosgjosjoskoskfosjofshohofshofusofhrehrhrehehhrehrherheheuorfos
    </span>
</div>

我需要:after 伪元素来占用&lt;span&gt; 中最后一行文本的宽度,而不是第一行。

将 inline-block 添加到 span,导致文本仅显示为块级元素,如 chrome 和 Firefox 39 中所示:

div {
    background-color: blue;
    text-align: center;
}
span {
    position: relative;
    background-color: green;
    display:inline-block;
    
}
span:after {
    content: '';
    display: block;
    position: absolute;
    left: 0;
    right: 0;
    height: 10px;
    width: 100%;
    background-color: red;
}
<div>
    <span>
        htejuteujetjthehtehtehethetje sghosgjosjoskoskfosjofshohofshofusethehetthehehterfos
    </span>
</div>

就好像&lt;span&gt;s min-width 设置为当所有文本都适合一行时&lt;span&gt; 将占据的长度。所以当窗口缩小时,文本分割成两行或更多行,宽度不能缩小到小于它的假设min-width...

有人有什么想法吗?最好不必更改 DOM,尽管如果绝对必要也可以这样做。

【问题讨论】:

    标签: html css width pseudo-element pseudo-class


    【解决方案1】:

    display:inline-block 添加到跨度样式

     span {
         position: relative;
         background-color: green;
         display:inline-block;
     }
    

    结果:

    【讨论】:

    • 这适用于 '
      ',但如果它被移除(就像在现实世界的场景中一样),那么 '' 再次变为宽度的 100%父母。
    • 好吧,即使没有&lt;br/&gt;,它也对我有用。也许这取决于浏览器?我在 Firefox 和 Chrome 中检查过。
    • i.imgur.com/Xw31q91.png -- 是我在 Firefox 39 中得到的...如您所见,蓝色消失了,绿色已完全接管。
    • jsfiddle.net/m03z5bmf Firefox 40.0.3,红线只在文字下方(也有&lt;br/&gt;
    • 你没有理解我的意思。蓝色不再可见,因为它内部有一个 100% 宽度的块级元素。跨度需要是内联的,而不是块元素...你能在浏览器中看到 blue 吗?
    【解决方案2】:

    您需要将跨度设置为块元素。 html

    <div>
    <span>
        htejuteujetjtje  sghosgjosjoskoskfosjofshohofshofusofuorfos
    </span>
    </div>
    

    CSS

    div {
    background-color: blue; 
    }
    span {
    position: relative;
    background-color: green;
    }
    
    span{display:block;}
    
    span:after {
    content: '';
    display: block;
    height: 10px;
    width: 100%;
    background-color: red;
    position: absolute;
    }
    

    【讨论】:

    • 显示块将使跨度成为父级的 100% 宽度。这不是我想要的。该元素必须是内联的,但使用最后一行,因为它是相对位置宽度...我已经更新了我的问题以更好地代表问题。
    猜你喜欢
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 2012-12-17
    相关资源
    最近更新 更多