盒子塌陷的原因
- 浮动导致的塌陷,浮动会脱落标准流
- 嵌套的两个盒子,子盒子设置margin-top会导致父盒子一下下移
父盒子默认定位
//css样式
<style>
.box{
+ position: static;
width: 300px;
height: 300px;
background-color: pink;
}
.son{
margin-top: 100px;
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
//html样式
<div class="box">
<div class="son"></div>
</div>
如图,产生塌陷
父盒子绝对定位
absolut脱离的文档流是相对于其父元素的,父元素的position属性不为static(static为position默认属性), 如果absolute所在元素的父元素position属性为static则其继续向上寻找,直到找到符合要求的父元素。脱离文档流之后其他元素会无视此元素,其此元素不再占据原本的位置
//css样式
<style>
.box{
+ position: absolute;
width: 300px;
height: 300px;
background-color: pink;
}
.son{
margin-top: 100px;
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
如图,效果图同上
父盒子固定定位
fixed:设置此属性的元素在位置上总是相对于body标签
//css样式
<style>
.box{
+ position: fixed;
width: 300px;
height: 300px;
background-color: pink;
}
.son{
margin-top: 100px;
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
效果图如下:
解决方法
清除浮动
给父元素添加overflow:hidden/overflow:auto;
.box{
//清除浮动
overflow: hidden;
}
缺点:当子元素有定位属性时overflow:auto
;有可能出现滚动条,影响美观。overflow:hidden
;可能会带来内容不可见的问题
给父盒子添加border边框
.box{
//边框
border: 1px solid #333;
}