天天看点

塌陷问题

嵌套元素塌陷

当父盒子和子盒子都同时拥有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>
           

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