塌陷问题

嵌套元素塌陷

当父盒子和子盒子都同时拥有margin-top时,都会使嵌套块元素塌陷

<style>
	.father {
		width: 400px;
		height:400px;
		margin-top:50px;
		background-color:black;
	}
	.son{
		width:200px;
		height:200px;
		background-color:red;
		margin-top:100px;	
	}
</style>
<div class="father">
	<div class="son">
	</div>
</div>

此时父盒子的上边距会变成100px,而子盒子相对于父盒子没有上边距
解决方法:

  1. 为父元素定义上边框。
  2. 为父元素定义上内边距
  3. 为父元素添加overflow:hidden。
<style>
	.father {
		width: 400px;
		height:400px;
		margin-top:50px;
		background-color:black;
		/*border-top:1px solid transpanrent;*/
		/*padding-top:1px;*/
		overflow:hidden; 
	}
	.son{
		width:200px;
		height:200px;
		background-color:red;
		margin-top:100px;	
	}
</style>
<div class="father">
	<div class="son">
	</div>
</div>

浮动和定位导致的塌陷解决方法

1.额外标签法

添加的标签必须是块级元素

<style>
	.box{
		width:500px;
		border:1px solid blue;
	}
	.one {
		width:200px;
		height:200px;
		float:left;
		background-color:red;
	}
	.clear {
		clear:both;
	}
	.footer {
		height:200px;
		background-color:black;
	}
</style>
<div class="box"> 
	<div class="one"></div>
	<div class="one"><div/>
	<div class="clear"></div>
</div>
<div class="footer"></div>

2.父级添加overflow

缺点:溢出部分会隐藏

<style>
	.box{
		width:500px;
		border:1px solid blue;
		overflow:hidden;
	}
	.one {
		width:200px;
		height:200px;
		float:left;
		background-color:red;
	}
	.footer {
		height:200px;
		background-color:black;
	}
</style>
<div class="box"> 
	<div class="one"></div>
	<div class="one"><div/>
</div>
<div class="footer"></div>

3.父级添加after伪元素

<style>
	.box{
		width:500px;
		border:1px solid blue;
	}
	.clearfix:after {
		content: "";
		display:block;
		height:0;
		clear:both;
	}
	.one {
		width:200px;
		height:200px;
		float:left;
		background-color:red;
	}
	.footer {
		height:200px;
		background-color:black;
	}
</style>
<div class="box clearfix"> 
	<div class="one"></div>
	<div class="one"><div/>
</div>
<div class="footer"></div>

4.父级添加双伪元素

<style>
	.box{
		width:500px;
		border:1px solid blue;
	}
	.clearfix:after,.clearfix:before {
		content:"";
		display:table;
	}
	.clearfix:after {
		clear:both;
	}
	.one {
		width:200px;
		height:200px;
		float:left;
		background-color:red;
	}
	.footer {
		height:200px;
		background-color:black;
	}
</style>
<div class="box clearfix"> 
	<div class="one"></div>
	<div class="one"><div/>
</div>
<div class="footer"></div>

以上是自己学习过程中总结出来的,有什么问题欢迎指正。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值