CSS - 根据最大宽度设置 span 元素的百分比宽度

3
我有两个包含文本的div,一个在另一个上方。底部文本为灰色,顶部文本为红色。我想能够使用CSS指定我要显示的顶部红色div的百分比部分。使用width: x%时,显示的顶部div的百分比是相对于整行而不是内容(文本)的。我想知道需要哪种CSS修复才能实现我的目标。 http://jsfiddle.net/8oodus0n/
<div class="text-container">
    <span class="text-grey">
        We love Stack Overflow
    </span>
    <span class="text-color">
        We love Stack Overflow
    </span>
</div> 

.text-grey, .text-color{
    position: absolute;
    font-size: 18px;
    font-family: arial;
    font-weight: 800;
}

.text-grey{
    color: grey;
}

.text-color{
    color: red;
    overflow-x: hidden;
    width: 20%;
    white-space:nowrap;
}    
1个回答

2
一种方法是将父元素.text-container相对定位,然后将display更改为inline-block。这样做,元素的宽度将由其内容决定,在本例中为文本。因此,子元素的宽度将遵循父元素的最大宽度。

为了使此方法起作用,只有一个元素应该是绝对定位的。原因是绝对定位的元素基本上从正常流中删除,因此如果两个元素都是绝对定位的,则父元素的宽度为0。因此,其中一个元素需要以正常位置定位,以确定父元素的宽度。

.text-color {
    position: absolute;
    left: 0;
    top: 0;
}
.text-container {
    position: relative;
    display: inline-block;
}

更新的示例

.text-container {
    position: relative;
    display: inline-block;
}
.text-grey, .text-color {
    font-size: 18px;
    font-family: arial;
    font-weight: 800;
}
.text-grey {
    color: grey;
}
.text-color {
    position: absolute;
    left: 0;
    top: 0;
    color: red;
    overflow-x: hidden;
    width: 50%;
    white-space:nowrap;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接