盒模型的外边距合并问题及解决方案

在网页布局中,有时需要设置css设置外边距(margin), 但是会出现css外边距合并(即重叠)的情况。什么是外边距合并的情况呐?怎么解决呐?

1.外边距的合并
css外边距合并(重叠)是指两个相邻的块级元素(兄弟元素),当上下两个边距相遇时,外边距会产生重叠的现象,且重叠后的外边距等于其中较大者。

示例:

<style type="text/css">
		#container div{
			width: 200px;
			height: 200px;
		}
		#d1{
			background-color: #f00;
			margin-bottom: 40px;
		}
		#d2{
			background-color:#7FFFD4;
			margin-top: 30px;
		}
	</style>
</head>
<body>
	<div id="container">
		<div id="d1"></div>
		<div id="d2"></div>
	</div>
</body>

效果:
在这里插入图片描述
本来两个元素之间应该是70px的间距。现在合并成40px,以大的为准。

2.解决方案:
在设计的时候规避
(1).单独写一个上外边距或者下外边距
(2).给下面的盒子设置定位(position: absolute;)
(3).给下面的盒子设置浮动(float: left;)
(4).给任意一个设置成行内块元素(display: inline-block;)

方法1效果:

<style type="text/css">
		#container div{
			width: 200px;
			height: 200px;
		}
		#d1{
			background-color: #f00;
			margin-bottom: 70px;
		}
		#d2{
			background-color:#7FFFD4;
		}
	</style>

在这里插入图片描述

方法2效果:

<style type="text/css">
		#container div{
			width: 200px;
			height: 200px;
		}
		#d1{
			background-color: #f00;
			margin-bottom: 40px;	
		}
		#d2{
			background-color:#7FFFD4;
			margin-top: 30px;
			position: absolute;
		}
	</style>

在这里插入图片描述
方法3效果:

<style type="text/css">
		#container div{
			width: 200px;
			height: 200px;
		}
		#d1{
			background-color: #f00;
			margin-bottom: 40px;	
		}
		#d2{
			background-color:#7FFFD4;
			margin-top: 30px;
			float: left;
		}
	</style>

在这里插入图片描述
方法4效果:

<style type="text/css">
		#container div{
			width: 200px;
			height: 200px;
		}
		#d1{
			background-color: #f00;
			margin-bottom: 40px;
		    display: inline-block;
		}
		#d2{
			background-color:#7FFFD4;
			margin-top: 30px;
		}
	</style>

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值