浮动后父级边框塌陷的四种解决办法
当设置某个元素浮动后 父级元素边框会出现塌陷问题,即,父级元素高为0.尽管clear可以清除浮动对其他元素造成的影响,但是依然解决不了父级边框塌陷问题。
以下为四种解决办法:
1. 设置父元素的高度
2. 给父元素添加overflow:hidden属性
3. 给父级添加伪类after
4. 在浮动元素后面添加空div
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.div1 {
width: 80%;
/* height: 500px; */
margin: 0 auto;
border: 1px solid #ccc;
/* overflow: hidden; */
}
.div1:after {
clear:both;
content: '';
display: block;
}
.div2 {
width: 100px;
height: 100px;
background-color: pink;
float: left;
}
.div3 {
width: 100px;
height: 100px;
background-color: blue;
}
.div4 {
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
<!-- <div style="clear:both;"></div> -->
</div>
<div class="div3"></div>
<div class="div4"></div>
</body>
</html>