gpt4 book ai didi

html - 我想完全掌握包含 div 的 'position: relative' 的概念

转载 作者:行者123 更新时间:2023-11-28 18:19:56 28 4
gpt4 key购买 nike

请耐心等待...请原谅我(可能)不正确的术语:

在下面的代码中,我不明白为什么要将包含(父)div 设置为“position:relative”,以便内部的 div 相对于父 div 定位(使用“position:absolute”)。我认为为了实现这一点,子 div 将被设置为“相对”于父级。我是否理解父 div 本质上是在对内部的其他 div 说“嘿,你们现在都可以相对于我定位了!”我有点希望它能以相反的方式工作。

例如我预计文本会定位到包含 div 的“相对”位置。有人可以解释为什么它会像这里那样工作吗?谢谢。

<div id="backgroundImage">
<h2 class="titleBox">I AM A TITLE</h2>
<p class="textBox">I am a description box</p>
</div>

#backgroundImage {
position: relative;
height: 225px;
width: 300px;
background-image: url (#);
}

.titleBox {
position: absolute;
top: 15px;
left: 0;
}

.textBox {
position: absolute;
bottom: 10px;
left: 0;

}

最佳答案

documentation解释得很好,但我会总结一下。

An element with position:relative is first laid out just like any static element ... shifted according to the top, bottom, left and right properties

position: relative可以相对于其父项进行调整(即使其父项是静态的)。

对于 position: absolute ,

the containing block is the nearest positioned ancestor. By “positioned” I mean an element whose position property is set to relative, absolute or fixed

也就是说,position: absolute 元素上的topbottom 等属性是相对于最近的包含元素的position 不同于static(包括relative)。

也就是说position: absolute元素仍然可以相对定位。

关于html - 我想完全掌握包含 div 的 'position: relative' 的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17163333/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com