英文:
Influence of margin-top of adjacent elements on a positioned element
问题
- 为什么绝对定位的元素会占用下方第二个元素的上外边距?
- 为什么它们的外边距没有合并,以便
.normal
元素从顶部边缘向后退 20px,而定位元素向后退 40px? - 为什么只有
margin-top
会生效,而margin-left
不会按照这种方式生效?
英文:
I have 2 elements, each given a margin-top of 20px. The first one is positioned absolutely. Naturally, the second element ends up at the top and recedes from the edge of the screen by 20px.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
div {
width: 200px;
height: 200px;
}
.posa {
margin-top: 20px;
position: absolute;
background-color: #1239;
}
.normal {
margin-top: 20px;
margin-left: 20px;
background-color: #aaa9;
}
<!-- language: lang-html -->
<div class="posa">position</div>
<div class="normal">normal</div>
<!-- end snippet -->
https://stackoverflow.com/questions/24373683/css-absolute-positioned-elements-and-margins - This question was almost answered here, but it was talking about the parent element
Questions:
- Why does an absolutely positioned element take the margin of the second element that was below?
- Why don't their margins collapse so that the
.normal
element will recede from the top edge by 20px and the positioned element will recede by 40px. - Why does only the margin-top affect and the margin-left doesn't work that way?
答案1
得分: 1
正常元素的 margin-top
与 body 的 margin 发生合并,因为它是流动子元素中的第一个,然后绝对定位的元素以 body 元素为参考向下移动。它使用了 静态位置,因为您没有指定任何 top/left/right/bottom 值。
为 body 元素添加轮廓以注意到这一点:
div {
width: 200px;
height: 200px;
}
.posa {
margin-top: 20px;
position: absolute;
background-color: #1239;
}
.normal {
margin-top: 20px;
margin-left: 20px;
background-color: #aaa9;
}
body {
outline: 1px solid red;
}
html {
outline: 1px solid blue;
outline-offset: -1px;
}
<div class="posa">position</div>
<div class="normal">normal</div>
左侧没有发生 margin 合并,因此正常元素的 margin 不会影响绝对定位元素的位置。
英文:
The margin-top
of the normal element is collapsing with the body margin since it's the first in-flow child then the absolute element is using the body element as reference to move down. It's using its static position since you didn't specify any top/left/right/bottom value
Add outline to the body element to notice this:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
div {
width: 200px;
height: 200px;
}
.posa {
margin-top: 20px;
position: absolute;
background-color: #1239;
}
.normal {
margin-top: 20px;
margin-left: 20px;
background-color: #aaa9;
}
body {
outline: 1px solid red;
}
html {
outline: 1px solid blue;
outline-offset: -1px;
}
<!-- language: lang-html -->
<div class="posa">position</div>
<div class="normal">normal</div>
<!-- end snippet -->
There is not margin collapsing on the left so the margin of the normal element will not affect the position of the absolute element.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论