一、浮动失效原因
(1)元素浮动,脱离文档流,覆盖常规元素
代码:
<style>
.div1{
float:left;
width:250px;
height:250px;
background-color:red;
}
.div2{
width:250px;
height:250px;
background-color:green;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
效果图:
解释: 红色浮动的div覆盖了原本文档流上绿色div。
(2)元素的定位设置为绝对定位(position:absolute)
代码:
<style>
.div1{
position:absolute;
float:right;
width:250px;
height:250px;
background-color:red;
}
.div2{
width:250px;
height:250px;
background-color:green;
}
</style>
</head>
<body>
<div >
<div class="div1"></div>
<div class="div2"></div>
</div>
</body>
效果图:
解释: 我们将红色div设置右浮动,但是能覆盖了原文档流中的绿色div,原因在于设置绝对定位后红色div仍浮动并且脱离文档流,因此覆盖了原文档流中绿色div,但是并没有实现右浮动。
(3)元素设置display:none
代码:
.div1{
display:none;
float:right;
width:250px;
height:250px;
background-color:red;
}
.div2{
width:250px;
height:250px;
background-color:green;
}
效果图:
解释: 与(2)不同在于,红色div右浮动但是隐藏了,绿色div按文档流占据左侧。
二、浮动后对盒子的影响
(1)左(右)浮动盒子向上向左(右)排列,并且浮动元素顶边不能高于上一个盒子的顶边,因此假如空间不够的时候,浮动元素会向下移动。
代码:
<style>
.contain{
width:500px;
height:500px;
background-color:yellow;
}
.div1{
float:left;
width:250px;
height:250px;
background-color:red;
}
.div2{
float:left;
width:300px;
height:250px;
background-color:green;
}
</style>
</head>
<body>
<div class="contain">
<div class="div1"></div>
<div class="div2"></div>
</div>
</body>
效果图:
解释: 容器宽500px,因为红绿两个div宽度和大于容器宽,绿色被挤到下一行。
(2)父元素无法被撑开,清除浮动
代码:
方法1:
父div结束前增加一个空div style=”clear:both;”
<div class="contain">
<div class="div1"></div>
<div class="div2"></div>
<div class="div1"></div>
<div class="div2"></div>
<div style="clear:both;"></div><!--父div结束前增加一个空div style=”clear:both;”-->
</div>
方法2:
css中添加
.clearfix::after{
content:"";
display:block;
clear:both;
}
父容器添加
<div class="contain clearfix">
<div class="div1"></div>
<div class="div2"></div>
<div class="div1"></div>
<div class="div2"></div>
</div>
效果图:
解释: 清除浮动,父容器被撑开。两种方法原理一样都是在父元素末尾添加一个block元素,再利用clear效果使该block元素位于浮动元素下方,因此父元素被撑开