提问:
浮动会让元素塌陷。即被浮动元素的父元素不具有高度。例如一个父元素包含了浮动元素,它将塌陷具有零高度。你可以按以下哪种方法处理浮动的影响呢?
# 回答:
1. 添加空标签法:
在最后添加一个空标签元素,然后设置这个空标签的清除浮动属性为:清除2侧浮动;
<style>
.float {
width: 500px;
background-color: pink;
}
.one {
width: 100px;
height: 100px;
background-color: #E67474;
}
.two {
width: 200px;
height: 200px;
background-color: #96C143;
}
.one,
.two {
float: left;
}
.clear {
clear: both;
}
</style>
<body>
<div class="float">
我孩子浮动了
<div class="one">浮动1</div>
<div class="two">浮动2</div>
<div class="clear"></div>
</div>
</body>
2. 给父元素添加 overflow
<style>
.float {
width: 500px;
background-color: pink;
overflow: hidden;
}
.one {
width: 100px;
height: 100px;
background-color: #E67474;
}
.two {
width: 200px;
height: 200px;
background-color: #96C143;
}
.one,
.two {
float: left;
}
</style>
<body>
<div class="float">
我孩子浮动了
<div class="one">浮动1</div>
<div class="two">浮动2</div>
</div>
</body>
3. 使用 alter 伪元素
定义一个样式,给他添加一个伪元素,然后设置到 子元素 浮动的 父元素上,和 第一种方法一样:
<style>
.float {
width: 500px;
background-color: pink;
}
.clearfix {
*zoom: 1;
}
.clearfix::after {
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.one {
width: 100px;
height: 100px;
background-color: #E67474;
}
.two {
width: 200px;
height: 200px;
background-color: #96C143;
}
.one,
.two {
float: left;
}
</style>
<body>
<div class="float clearfix">
我孩子浮动了
<div class="one">浮动1</div>
<div class="two">浮动2</div>
</div>
</body>