html
同day4一样
css
题目:清除浮动的方式有哪些,原理是啥,有啥优缺点
答案:
ps:为啥要清除浮动:子元素浮动后,脱离文档流,不再被父元素包裹,故父元素高度坍塌,无法由子元素撑开
1、手动给父元素要给高度;兼容性好,但自适应差;
2、触发父元素BFC,让内层子元素不影响外层父元素样式
给父元素:overflow: auto;
可能会出现滚动条
2、新增一个空元素清除浮动
新增了冗余的元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
padding: 10px 10px;
background-color: yellowgreen;
}
.item {
float: left;
width: 10px;
height: 10px;
background-color: blue;
list-style: none;
}
// 重点
.clear-item {
clear: both;
}
</style>
</head>
<body>
<ul class="box">
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<!-- 重点 -->
<div class="clear-item"></div>
</ul>
</body>
</html>
3、使用after伪元素清除浮动
低版本IE不兼容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
padding: 10px 10px;
background-color: yellowgreen;
}
.item {
float: left;
width: 10px;
height: 10px;
background-color: blue;
list-style: none;
}
// 重点
.box::after {
content: '';
display: block;
clear: both;
}
</style>
</head>
<body>
<ul class="box">
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ul>
</body>
</html>