CSS解决外边距塌陷问题
CSS外边距塌陷
<div class="father">
<div class="son"></div>
</div>
当我们为子元素设置margin-top可能会遇到以下问题:
在为子元素设置margin-top会将父元素一起拖下来这是因为:
- 元素为嵌套元素(即父元素与子元素)
- 父元素与子元素在垂直方向上的外边距合并(margin-top和margin-bottom)
要解决这个问题,我们可以使用以下方法
1. 父元素添加顶部padding
CSS样式.father {
padding-top: 1px; /* 任意大小均可 */
width: 500px;
height: 500px;
background-color: red;
}
.son{
width: 100px;
height: 100px;
background-color: blue;
}
2. 父元素添加顶部border
CSS样式.father {
border-top: 1px solid transparent;
width: 500px;
height: 500px;
background-color: red;
}
.son {
margin-top: 200px;
width: 100px;
height: 100px;
background-color: blue;
}
3. 父元素/子元素设置为绝对定位
CSS样式.father {
position: absolute;
width: 500px;
height: 500px;
background-color: red;
}
.son {
/* position: absolute; */
margin-top: 200px;
width: 100px;
height: 100px;
background-color: blue;
}
CSS样式 4. 父元素设置overflow: auto/hidden
.father {
overflow: auto;
/* overflow: hidden; */
width: 500px;
height: 500px;
background-color: red;
}
.son {
margin-top: 200px;
width: 100px;
height: 100px;
background-color: blue;
}
5. 父元素设置display: flex
CSS样式.father {
display: flex;
width: 500px;
height: 500px;
background-color: red;
}
.son {
margin-top: 200px;
width: 100px;
height: 100px;
background-color: blue;
}
6. 父元素/子元素设置为浮动元素
CSS样式.father {
float: left;
display: flex;
width: 500px;
height: 500px;
background-color: red;
}
.son {
/* float: left; */
margin-top: 200px;
width: 100px;
height: 100px;
background-color: blue;
}
7. 父元素设置display: table
CSS样式.father {
display: table;
width: 500px;
height: 500px;
background-color: red;
}
.son {
margin-top: 200px;
width: 100px;
height: 100px;
background-color: blue;
}