如何让下面的代码中的 #row1
和 #row2
在垂直方向上一个接一个地可见,就好像没有涉及任何 absolute/relative
定位 ca尽管没有删除定位属性)?即有两个 .row
<div>
显示为“正常”块元素。
body { position:relative; min-height: 2em; width: 100%; }
.container {position:absolute;}
.row {position:relative;}
.col1, .col2 {position: absolute;}
<body>
<div class="container">
<div id="row1" class="row">
<div class="col1">Hello</div>
<div class="col2">World</div>
</div>
<div id="row2" class="row">
<div class="col1">Salut</div>
<div class="col2">le monde</div>
</div>
</div>
</body>
(样本也可作为 小提琴 使用。)
由于此处排除的原因,我需要元素具有 CSS 规则中提供的定位。
内容在程序上是动态的;我事先不知道元素的高度,所以解决方案不能基于在任何地方指定绝对长度(例如’px’)。
原文由 Fellow Stranger 发布,翻译遵循 CC BY-SA 4.0 许可协议
好吧,你有一些奇怪的愿望,所以让我向你解释一下这些位置在 CSS 中的真正含义以及它们是如何工作的,使用
position: relative;
就像使用static
position
, the difference is making an elementposition: relative;
, you will be able to usetop
,right
,bottom
andleft
属性,虽然元素会移动,但实际上它会在文档流中..来到
position: absolute;
,当你制作任何元素position: absolute;
时,它脱离了文档流,因此,它与任何其他元素无关,所以在你的例子中你有.col1, .col2 {position: absolute;}
位于absolute
并且由于两者都不在文档流中,它们将重叠…因为它们已经嵌套在position: absolute;
.container
因为没有分配width
,它将占用最小的width
因此,你的元素重叠,如果你不能改变我的 CSS’t明白为什么你不能改变)仍然如果你愿意,你能做的就是这个..演示(不删除您的任何
position
属性)这真的很脏对于
s
字符,它将位于top
因为您的容器元素不在流中,因此,文档中不会考虑height
流,除非并且直到你将s
包装在某个元素中,并用margin
padding
或 CSS 定位。CSS 位置解释
正如我所评论的,这里有几个 CSS 定位实际如何工作的例子,首先,
position
属性有 4 个值,即static
这是默认值,relative
,absolute
和fixed
, 所以从static
开始display: inline-block
。 Withstatic
positioning,top
,right
,bottom
andleft
won’t work.演示
来到
position: relative;
我已经向你解释了一般情况,它与static
一样,它堆叠在其他元素上,它在文档流中,但你可以调整elementsposition
usingtop
,right
,bottom
andleft
, physically, the element stays in the flow,只有元素的position
发生了变化。演示 2
现在来
absolute
这通常很多人无法理解,在制作元素时absolute
它脱离了文档流,因此保持独立,与其他元素定位无关除非它被其他position: absolute
元素重叠,可以使用z-index
更改堆栈级别。这里要记住的主要事情是有一个position: relative;
容器,这样你的absolute
定位的元素是 相 对于那个relative
定位的元素,否则你的元素将飞出元素在野外。值得注意的是
position: absolute;
元素定位absolute;
内部absolute
定位父元素,而 不是相 对于哪个父元素可能位于relative
演示 3 (没有
position: relative;
容器)演示 4 (使用
position: relative;
容器)最后是
position fixed
,这与absolute
相同,但是当你滚动时它会流动,它不在文档流中,但它也会滚动position: fixed;
element cannot berelative
to any container element having any type ofposition
, not evenrelative
,position
fixed
element is alwaysrelative
to the viewport, so designers useposition: absolute;
when they want to have afixed
position
behavior butrelative
父级并调整top
属性onScroll
。演示 5