嵌套元素塌陷
當父盒子和子盒子都同時擁有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,而子盒子相對于父盒子沒有上邊距
解決方法:
- 為父元素定義上邊框。
- 為父元素定義上内邊距
- 為父元素添加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>
以上是自己學習過程中總結出來的,有什麼問題歡迎指正。