CSS - 设置跨度的宽度相对于其最大宽度的百分比
CSS - Setting the width of a span in % with respect to its maximum width
我有两个 div 包含相互堆叠的文本。底部文本为灰色,顶部文本为红色。我希望能够指定我想用 CSS 显示的顶部红色 div 部分的百分比。使用 width: x%
时,显示的顶部 div 的百分比是相对于整行而不是内容(文本)。我想知道完成我想要的 CSS 所需的修复。
<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;
}
一种方法是相对定位父元素 .text-container
,然后将 display
更改为 inline-block
。这样做时,元素的宽度将由其内容决定,在本例中为文本。因此,子 span 元素的宽度将遵循父元素的最大宽度。
为了让它工作,只有 span
元素之一应该是绝对定位的。这样做的原因是因为绝对定位的元素基本上从正常流中移除,因此如果两个元素都是绝对定位的,则父元素的宽度为 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;
}
我有两个 div 包含相互堆叠的文本。底部文本为灰色,顶部文本为红色。我希望能够指定我想用 CSS 显示的顶部红色 div 部分的百分比。使用 width: x%
时,显示的顶部 div 的百分比是相对于整行而不是内容(文本)。我想知道完成我想要的 CSS 所需的修复。
<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;
}
一种方法是相对定位父元素 .text-container
,然后将 display
更改为 inline-block
。这样做时,元素的宽度将由其内容决定,在本例中为文本。因此,子 span 元素的宽度将遵循父元素的最大宽度。
为了让它工作,只有 span
元素之一应该是绝对定位的。这样做的原因是因为绝对定位的元素基本上从正常流中移除,因此如果两个元素都是绝对定位的,则父元素的宽度为 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;
}