HTML+CSS 中浮动样式
在编写 html 样式的时候难免会遇到元素使用浮动属性导致元素样式坍塌的情况,我们使用清除浮动来解决样式坍塌问题。
注意
- 浮动元素不会覆盖文字内容
- 浮动元素不会覆盖图片内容
- 浮动元素不会覆盖表单元素(输入框、单选按钮、复选框、按钮、下拉选择框等等)
坍塌示例
解决坍塌问题后示例效果
在这里给出基本结构代码,以下有几种示例方法能够解决浮动导致的布局坍塌
<!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 {
float: left;
}
.box:nth-child(1) {
width: 20%;
background-color: red;
height: 50px;
}
.box:nth-child(2) {
width: 30%;
background-color: pink;
height: 80px;
}
.box:nth-child(3) {
width: 50%;
background-color: blue;
height: 100px;
}
.other {
background: gray;
width: 100%;
height: 100px;
}
</style>
</head>
<body>
<div class="outer">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="other"></div>
</body>
</html>
1.给父元素添加 overflow 属性
.outer {
overflow: auto;
}
2. 给浮动元素后面的元素添加 clear 属性
.clearfix {
clear: both;
}
<body>
<div class="outer">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="other clearfix"></div>
</body>
3.给父元素添加固定的高度
如果子元素的高度大于父元素所设定的高度这种方式会导致内容溢出,
可以设置 overflow:hidden;隐藏溢出的内容
.outer {
height: 100px;
/* overflow:hidden; */
}
4. :after 伪元素
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
zoom: 1; /* IE 6 7*/
}
<body>
<div class="outer clearfix">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="other"></div>
</body>
5.使用 before 和 after 双伪元素清除浮动
.clearfix:before,
.clearfix:after {
content: "";
display: block;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1; /* IE 6 7*/
}
<body>
<div class="outer clearfix">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="other"></div>
</body>