float CSS属性指定一个元素应沿其容器的左侧或右侧放置,容许文本和内联元素环绕它。该元素从网页的正常流动中移除,尽管仍然保持部分的流动性。css
浮动元素是float值不为none的元素。html
可能值:布局
float意味着使用块布局。flex
float会将所应用元素的display值修改成block。即若是元素自己的display为inline、inline-block、inline-table、table-row、table-row-group、table-column、table-column-group、table-cell等,那么变为浮动元素后该display值会被修改成block。3d
float对flex、inline-flex不起做用。若是元素的display为flex、inline-flex,则不会被修改,由于float对它们不起做用。code
当一个元素浮动以后,它会被移除正常的文档流,而后向左或向右平移,一直平移直到碰到所处容器的边框,或者碰到另一个浮动的元素。htm
正常的浮动定位效果的实现须要知足前提条件:浮动元素的高度比其所在容器的高度小。blog
若是浮动元素的高度比其所在容器的高度大。那么容器也不会被该浮动元素撑大,因此容器下面的兄弟元素也会跑到浮动元素的一侧。若是不想要浮动元素也浮动在容器接下来的兄弟元素的一侧,那么须要对容器的该兄弟元素进行 清除浮动(clear属性)。文档
代码:get
<div class="container"> <div class="item float1"> float1 </div> <div class="item float2"> float2 </div> <div class="item float3"> float3 </div> 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵哈哈哈哈哈哈哈 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵哈哈哈哈哈哈哈 </div>
.container{ background: yellow; } .item { width: 100px; height: 100px; } .float1 { background: red; float: left; } .float2 { background: blue; float: left; } .float3 { background: orange; float:right; }
效果:
代码:
<div class="container"> <div class="item float1"> float1 </div> <div class="item float2"> float2 </div> <div class="item float3"> float3 </div> 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈 </div> <div class="otherbox"> 啦啦啦 </div>
.container{ background: yellow; } .item { width: 100px; height: 100px; } .float1 { background: red; float: left; } .float2 { background: blue; float: left; } .float3 { background: orange; float:right; } .otherbox { background: green; }
效果:
代码:
在2.的基础上,给.otherbox的样式改成:
.otherbox { background: green; clear: both; }
效果:
若是仅仅只clear一边的浮动元素:
.container{ background: yellow; } .item { width: 100px; height: 100px; } .float1 { background: red; float: left; } .float2 { background: blue; float: left; } .float3 { background: orange; height: 200px; /*为了看清清楚左右浮动的区别,将float3高度改成200px*/ float:right; } .otherbox { background: green; clear: left; }
效果:
clear:right效果同理。