首先来模拟个发生浮动的样式代码
<div>
<div id="fatherDiv">
<div id="child1">child1</div>
<div id="child2">child2</div>
</div>
<div id="otherDiv">otherDiv</div>
</div>
<style>
#fatherDiv{
background: aqua;
}
#child1{
background: beige;
float: left;
}
#child2{
background: #42b983;
float: left;
}
</style>
1. 定义父级div的和height
#fatherDiv{ height: 100px;//高度大于浮动元素高度 }
缺点: 只适合高度确定的情况
2.结尾处加空的div块 diva 给diva添加clear:both样式
<div id="fatherDiv">
<div id="child1">child1</div>
<div id="child2">child2</div>
<div id="ocuppyDiv"></div>
</div>
<div id="otherDiv">otherDiv</div>
<style scoped>
#ocuppyDiv{
clear: both;
}
</style>
缺点 增加了html标签
3.父级div定义伪类:after
#fatherDiv:after{ display:block; clear:both; content:"" }
4.父级div定义overflow
#fatherDiv{
background: aqua;
auto;
overflow: hidden;
}
5.父级div设置(dispaly:table)
#fatherDiv{
display: table;
}
6 浮动元素后面加个br标签
<div>
<div id="fatherDiv">
<div id="child1">child1</div>
<div id="child2">child2</div>
<!-- 方法二 <div id="ocuppyDiv"></div>-->
</div>
<!-- 方法六 <br>-->
<div id="otherDiv">otherDiv</div>
</div>