<style type="text/css">
* {
box-sizing: border-box;
}
#max-box {
width: 500px;
height: 500px;
background-color: aliceblue;
margin: 0 auto;
/*position: relative;*/
/*padding: 10px 10px;*/
}
#min-box {
/*position: absolute;*/
width: 300px;
height: 300px;
background-color: #4169E1;
margin: 30px 100px 100px;
}
</style>
<body>
<p id="max-box">
<p id="min-box">
</p>
</p>
</body>
如图、我并没有给父元素 max-box 加 margin,但是也被撑高了
First of all, this has nothing to do with
box-sizing
. The situation mentioned by the questioner will happen regardless of whether it is set or not.This phenomenon is called Collapsing Margins, which is mentioned in w3c’s CSS2.2 specification document - collapsing margins:
What is mentioned here are the conditions for vertical margin merging, and they must be met at the same time. In the subject's example, it is the case of "top margin of a box and top margin of its first in-flow child". In addition, there are no "isolating elements" such as inline text and padding between them, so it will change. Like this.
Correspondingly, as long as some states are changed, vertical margin merging can be avoided. The
position: absolute;
commented out by the subject is one of them.This is a problem with CSS style margin overlay:
If two adjacent elements have margins, the larger of the two will be used as the spacing distance;
Similarly, for the two included elements Likewise, the special thing is that if there are two elements included, the parent element has no margin, and the child element has margin, and the parent element does not have border and padding, then the margin of the child element will overflow outside the parent element. To solve this problem, there are There are many methods, such as setting 1px padding or setting a transparent border, to prevent margin overflow.
Set the parent element: overflow: hidden;
The margin-top of the small p is 30px
It’s not because of the box-sizing problem. The margin-top of the min-box is 30px, which will affect the parent element to have a margin-top along with it. Add an overflow: hidden to the max-box; that’s it
Details and usage of margin collapsingCollapsing Margins