效果图
![](https://i-blog.csdnimg.cn/direct/d249c25d0f414dbd8569c6529e4c5cbb.png)
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>清除浮动和解决外边距塌陷</title>
<style>
* {
margin: 0px;
padding: 0px;
}
ul {
width: 240px;
background-color: #ffe4c4;
/* 清楚浮动方式一:给父元素设置如下属性 */
/* overflow: hidden; */
}
/* 清除浮动方式二:给父元素添加 clearfix 类名 */
.clearfix::before,
.clearfix::after {
content: "";
display: table;
}
.clearfix::after {
clear: both;
}
/* 推荐方式二,既能解决外边距塌陷问题,又能清除浮动
before解决外边距塌陷问题
after清除浮动 */
ul li {
float: left;
margin: 5px;
width: 50px;
height: 100px;
background-color: #0ff;
list-style: none;
}
div {
width: 300px;
height: 100px;
background-color: #a52a2a;
}
</style>
</head>
<body>
<ul class="clearfix">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div></div>
</body>
</html>