Solution to the problem of margin collapse

A problem phenomenon in the daily code:
obviously set the margin-top attribute in the child div, but it has no effect. On the contrary, when the value of the margin-top attribute of the child div is greater than the value of the parent div's margin-top At this time, the entire structure moves down instead of the margin distance between the child div and the top of the parent div.

<div class="wrapper">
	<div class="content"></div>
</div>  	

.wrapper {
	margin-left: 100px;
	margin-top: 100px;
	width: 100px;
	height: 100px;
	background-color: black;
}
.content {
	width: 50px;
	height: 50px;
	margin-top: 50px;
	margin-left: 50px;
	background-color: #00f;
}

Insert picture description here
At this point, after setting the attribute border-top for the parent div, the child div successfully has a margin distance from the parent div.

<div class="wrapper">
	<div class="content"></div>
</div>  	

.wrapper {
	margin-left: 100px;
	margin-top: 100px;
	width: 100px;
	height: 100px;
	background-color: black;
	border-top: 1px solid #fff;
}
.content {
	width: 50px;
	height: 50px;
	margin-top: 50px;
	margin-left: 50px;
	background-color: #00f;
}

Insert picture description here
However, this implementation method obviously does not conform to the encoding method.
Therefore, there are the following methods to solve this phenomenon. Change the grammar rules of the box.
Add one of the attributes to the parent div

overflow:hidden;
display:inline-block;
float: left;
position: absolute;
can trigger bfc to achieve the effect (the following is an example of overflow),
but there is no so-called optimal method among these methods, which should be selected according to specific needs Appropriate method to solve the bug of margin collapse



.wrapper {
	margin-left: 100px;
	margin-top: 100px;
	width: 100px;
	height: 100px;
	background-color: black;
	overflow: hidden;
}
.content {
	width: 50px;
	height: 50px;
	margin-top: 50px;
	margin-left: 50px;
	background-color: #00f;
}

Guess you like

Origin blog.csdn.net/m0_38038767/article/details/88211259