"Outer margin merging" and "margin top collapse" of box model in web

Outer margin merge

In the case of nested box models, when two vertical outer margins meet, they will form an outer margin. The height of the combined outer margin is equal to the greater of the height of the two merged outer margins.

The solution is as follows:

1. Use this feature

For example:

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.box{
			width: 500px;
			border: 1px solid #000;
			margin:50px auto 0;
			
		}

		.box div{
			/*margin-left: 20px;
			margin-right: 20px;
			margin-top: 20px; 
			margin-bottom: 20px;*/
			margin:20px; 
		}

	</style>
</head>
<body>
	<div class="box">
		<div>Outer margin merging means that when two vertical outer margins meet, they form an outer margin. The height of the combined outer margin is equal to the greater of the height of the two merged outer margins.</div>
		<div>Outer margin merging means that when two vertical outer margins meet, they form an outer margin. The height of the combined outer margin is equal to the greater of the height of the two merged outer margins.</div>
		<div>Outer margin merging means that when two vertical outer margins meet, they form an outer margin. The height of the combined outer margin is equal to the greater of the height of the two merged outer margins.</div>
		<div>Outer margin merging means that when two vertical outer margins meet, they form an outer margin. The height of the combined outer margin is equal to the greater of the height of the two merged outer margins.</div>
	</div>
</body>
</html>

2. Set the outer margin of one side, generally setting margin top

3. Floating or positioning elements

 

Margin top collapse

When two boxes are nested, the internal box's margin top will be added to the external box (especially when you want to set the internal box to be centered), which causes the internal box's margin top setting to fail. Only the top direction has this bug.

The solution is as follows:

1. Set a border on the external box

2. overflow:hidden

3. Use pseudo element class:

clearfix:before{
    content: '';
    display:table;
}
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		
		.clearfix:before{
			content: "";
			display: table;
		}

		.con{
			width: 300px;
			height: 300px;
			background-color: gold;
			/*border: 1px solid; The first way to solve the collapse*/
			
			/*overflow: hidden; The second method to solve the collapse*/
		}

		.box{
			width: 200px;
			height: 100px;
			background-color: green;
			margin-top: 100px;/*margin-top Collapse*/
			margin-left: 50px;/*No collapse in other directions*/
		}
	</style>
</head>
<body>
	<div class="con clearfix">
		<div class="box"></div>
	</div>
</body>
</html>

Posted by dfarrar on Sun, 17 Nov 2019 09:43:40 -0800