当你使用position:absolute;
,该元素被从正常页面流中取出。因此它不再影响其容器元素的布局。所以容器元素不考虑它的高度,所以如果没有其他东西来设置高度,那么容器的高度将为零。
另外,设置display:inline-block;
对于以下元素没有任何意义position:absolute;
。同样,这是因为绝对定位使元素脱离了页面流。这与inline-block
,它的存在只是为了影响元素如何适应页面流。所有元素都是position:absolute;
被自动视为display:block
,因为这是绝对定位的唯一逻辑显示模式。
If you need绝对定位,那么解决你的高度问题的唯一办法就是设置容器盒子的高度。
不过,我怀疑你可以不用绝对定位。
看来您要做的就是定位第二个<span>
将每个块移动到块中的固定位置,使它们对齐。
这是一个经典的 CSS 问题。在“糟糕的旧时代”,网页设计师会使用表格来完成此操作,表格单元格的宽度固定。这显然不是当今网页设计师的答案,但却引起了很多问题。
使用 CSS 有多种方法可以做到这一点。
最简单的方法是同时设置<span>
元素到display:inline-block;
,并给它们两个固定的宽度。
eg:
<div class='section'>
<span class="element-left">some text</span>
<span class="element-right">some text</span>
</div>
使用以下 CSS:
.section span {display:inline-block;}
.element-left {width:200px;}
.element-right {width:150px;}
[EDIT]问题更新后
以下是我如何实现您现在所要求的:
<div class='section'>
<span class="element-left"><span class='indent-0'>some text</span></span>
<span class="element-right">some text</span>
</div>
<div class='section'>
<span class="element-left"><span class='indent-1'>some text</span></span>
<span class="element-right">some text</span>
</div>
<div class='section'>
<span class="element-left"><span class='indent-2'>some text</span></span>
<span class="element-right">some text</span>
</div>
使用以下 CSS:
.section span {display:inline-block;}
.element-left {width:200px;}
.indent-1 {padding:10px;}
.indent-2 {padding:20px;}
.element-right {width:150px;}
少量的额外标记,但确实达到了你想要的效果。