margin塌陷和margin合并问题及解决方案

一,margin塌陷 

父子嵌套元素在垂直方向的margin,父子元素是结合在一起的,他们两个的margin会取其中最大的值.

正常情况下,父级元素应该相对浏览器进行定位,子级相对父级定位.

但由于margin的塌陷,父级相对浏览器定位.而子级没有相对父级定位,子级相对父级,就像坍塌了一样.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			.parent{
				width: 100px;
				height: 100px;
				background-color: red;
			}
			.child{
				width: 50px;
				height: 50px;
				background-color: green;
			}
		</style>
	</head>
	<body>
		<div class="parent">
			<div class="child"></div>
		</div>
	</body>
</html>

margin塌陷解决方法

1.给父级设置边框或内边距(不建议使用)

2.改变父级的渲染规则。有以下四种方法,给父级盒子添加    (推荐overflow:hidden)

(1)position:absolute/fixed

(2)display:inline-block;

(3)float:left/right

(4)overflow:hidden/auto/scroll

注意:只有垂直方向存在margin塌陷和合并,水平方向是正常的,即水平方向上子元素是正常相对父元素的,只是垂直方向上需要注意塌陷和合并问题

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			.parent{
				width: 100px;
				height: 100px;
				background-color: red;
				margin-top: 100px; 
				margin-left: 100px;
				
				/* 解决margin塌陷问题,以下四种方式都可以.推荐overflow: hidden; */
				overflow: hidden;
				/* position: absolute; */
				/* float: left; */
				/* display: inline-block; */
			}
			.child{
				width: 50px;
				height: 50px;
				background-color: green;
				margin-top: 20px;
				margin-left: 20px;
			}
		</style>
	</head>
	<body>
		<div class="parent">
			<div class="child"></div>
		</div>
	</body>
</html>

二,margin合并

两个兄弟结构的元素在垂直方向上的margin是合并的

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}
			.box1 {
				height: 30px;
				margin-bottom: 50px;
				background-color: red;
			}
			.box2 {
				height: 30px;
				margin-top: 50px;
				background-color: green;
			}
		</style>
	</head>
	<body>
		<div class="box1"></div>
		<div class="box2"></div>
	</body>
</html>

当把box2的margin-top设为100px后,box1和box2之间的margin就取最大的那个数,即100px>50px,所以margin为100px。

margin合并的解决方案:

1.给box2加上一层父级元素并加上overflow:hidden;

2.给两个都加一层父级再加bfc

但是这两种方法都改变了HTML结构,在开发中是不能采用的

在实际应用时,在margin合并这个问题上,我们一般不用bfc,而是通过只设置上面的元素的margin-bottom来解决距离的问题

两个兄弟结构的元素在水平方向上的margin是正常的,不存在合并现象

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}
			.parent{
				float: left;
			}
			.child_left{
				width: 50px;
				height: 50px;
				background-color: red;
				float: left;
				margin-right: 50px;
			}
			.child_right{
				width: 50px;
				height: 50px;
				background-color: green;
				float: left;
				margin-left: 50px;
			}
		</style>
	</head>
	<body>
		<div class="parent">
			<div class="child_left"></div>
			<div class="child_right"></div>
		</div>
	</body>
</html>

发布了319 篇原创文章 · 获赞 124 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_40323256/article/details/102754535