当盒子浮动时,会产生高度塌陷,运用清除浮动的方法,让我们得到想要的的网页样式。
我们想要的格式:
但是由于上面黄、蓝盒子浮动, 会导致红盒子上移效果如下:
我们得到 想要的效果就需要清除黄蓝盒子的 浮动效果 对红盒子的影响,以下有几个办法:
1)给浮动盒子写固定高度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1,.box2{
width: 200px;
height: 200px;
float: left;
}
.box1{
background: yellow;
}
.box2{
background: blue;
}
.box{
width: 300px;
height: 300px;
background: red;
}
.container{
height: 200px;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box"></div>
</body>
</html>
2)运用clear属性(可 left、right、none) 清除浮动 加在受影响的元素身上
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1,.box2{
width: 200px;
height: 200px;
float: left;
}
.box1{
background: yellow;
}
.box2{
background: blue;
}
.box{
width: 300px;
height: 300px;
background: red;
clear:left;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box"></div>
</body>
</html>
3)在当前浮动元素后面补一个盒子,不设置宽高
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1,.box2{
width: 200px;
height: 200px;
float: left;
}
.box1{
background: yellow;
}
.box2{
background: blue;
}
.box{
width: 300px;
height: 300px;
background: red;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
<div style="clear:left;"></div>
</div>
<div class="box"></div>
</body>
</html>
4)overflow:hidden,当浮动元素计算高度:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1,.box2{
width: 200px;
height: 200px;
float: left;
}
.box1{
background: yellow;
}
.box2{
background: blue;
}
.box{
width: 300px;
height: 300px;
background: red;
}
.container{
overflow:hidden;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
</div>
<div class="box"></div>
</body>
</html>