为什么要清除浮动
div1 盒子里有Left和Right 两个子盒子,div1 有兄弟盒子div2,给Left、Right 盒子添加浮动前效果图:
浮动的属性虽然方便使用,但是在使用这种属性时,也存在着一种弊端,那就是当子元素设置了float属性之后,且父元素的高度没有设置, 而是由子元素支撑起来,则会导致父元素的高度塌陷(原本的height后来被置为0)。所以这里我们说的清除浮动,指的是清除子盒子添加浮动效果后造成的父盒子高度塌陷。
给Left、Right 盒子添加浮动后效果图:
清除浮动的方式
1、clear:both
2、父级div 定义 overflow:hidden
3、父级div定义伪类:after和zoom(用于非IE浏览器)
4、父级div定义height
5、父级div定义overflow:auto
清除浮动后的效果图:
HTML 代码片段示例
<button id="addFloat">添加浮动</button>
<button id="back">返回浮动前</button>
<p></p>
<div class="div1" id="parentDiv">
<div id="left">Left</div>
<div id="right">Right</div>
</div>
<div class="div2">div2</div>
<h1>清除浮动</h1>
<ul>
<li ><button id="clearBoth">clear:both</button></li>
<li><button id="overflowHidden">父级div 定义 overflow:hidden</button> </li>
<li><button id="fakeClass">父级div定义伪类:after和zoom(用于非IE浏览器)</button></li>
<li><button id="addHeight">父级div定义height</button></li>
<li> <button id="overflowAuto">父级div定义overflow:auto</button></li>
</ul>
JS 代码示例
let addFloat = document.getElementById('addFloat')
let leftDiv = document.getElementById('left')
let rightDiv = document.getElementById('right')
let clearBoth = document.getElementById('clearBoth')
let overflowHidden = document.getElementById('overflowHidden')
let parentDiv = document.getElementById('parentDiv')
let back = document.getElementById('back')
let fakeClass = document.getElementById('fakeClass')
let addHeight = document.getElementById('addHeight')
let overflowAuto = document.getElementById('overflowAuto')
addFloat.onclick = function(){
leftDiv.style.float = 'left'
rightDiv.style.float = 'right'
}
back.onclick=function(){
location.reload()
}
clearBoth.onclick=function(){
let newDiv = document.createElement('div')
newDiv.style.clear="both"
parentDiv.parentNode.insertBefore(newDiv, parentDiv.nextElementSibling)
}
overflowHidden.onclick=function(){
parentDiv.style.overflow = 'hidden'
}
fakeClass.onclick=function(){
parentDiv.className+=' clearFloat'
}
addHeight.onclick = function () {
parentDiv.style.height = '100px'
}
overflowAuto.onclick = function () {
parentDiv.style.overflow = 'auto'
}
CSS 代码示例
.div1{
width:100px;
/* height: 100px; */
background-color: blue;
}
#left{
width:50px;
height: 100px;
background-color: burlywood;
}
#right{
width:50px;
height: 100px;
background-color: hotpink;
}
.div2{
width:120px;
height:120px;
background-color: blueviolet;
}
.clearFloat:after{
display: block;
clear: both;
content: '';
visibility: hidden;
height: 0;
}
.clearFloat{
zoom: 1;
}
完整演示页面HTML+CSS+JS代码下载链接:点击下载