块级元素互相嵌套会造成盒子塌陷问题
如: div { width: 300px; height: 300px; background-color: skyblue; }
p {
width: 200px;
height: 200px;
background-color: pink;
给子元素添加外边距作用会在父元素上
margin-top: 50px;
}
</style>
方法1:给父级元素添加padding-top,或者border-top
div {
width: 300px;
height: 300px;
background-color: skyblue;
padding-top: 1px;
border-top:solid 1px transparent;
}
方法2:给父元素添加 overflow: hidden;
div {
width: 300px;
height: 300px;
background-color: skyblue;
overflow: hidden;
}
方法3:设置浮动 float
div {
width: 300px;
height: 300px;
background-color: skyblue;
overflow: hidden;
float: left;
}
p {
width: 200px;
height: 200px;
background-color: pink;
margin-top: 50px;
float: left;
}
方法4:转换元素 display: inline-block;
p {
width: 200px;
height: 200px;
background-color: pink;
margin-top: 50px;
display: inline-block;
}
\