首页 > 技术文章 > float属性

yangzhinian 2015-10-25 11:41 原文

float属性介绍

float给人一种捉摸不透的感觉,不过可以依照浏览器的解析机制(根据HTML文档,从上往下解析),对float属性了解一二。float有四种值:none/left/right/inherit,我们主要关注的是left/right。

float的出现,最初是为了实现图文环绕的效果,后来渐渐的也被用于其他方面,实现一些特殊的排版。

float的特性

1、float元素存在占位,并未完全脱离文档流;float元素虽然脱离了父元素,不过会影响行内元素(inline/inline-block)。如:

<div style="background:#00f;color: #fff;">
    父元素中的行内元素
    <div style="float: left;width: 100px;height: 50px;background: #f00;">float元素</div>
</div>
<span style="display:inline-block;background: #0f0;">我是行内元素</span>

效果:

 

2、absolute元素是可以通过top/bottom/left/right调整自己的位置,而float元素受其他元素的影响,通过其他元素确定自身的位置,如:

<div style="background: #f00;">我是块级元素,float元素在下面</div>
<div style="background: #00f;width: 100px;height: 50px;float: left;">float</div>

效果:

3、float元素之间在占位上是相互影响的,而absolute元素即使处于同一层,在占位上是互不影响的。如:

<!-- absolute1被absolute2覆盖了 -->
<div style="background: #f00;width: 100px;height: 50px;position: absolute;">absolute1</div>
<div style="background: #00f;width: 100px;height: 50px;position: absolute;">absolute2</div>
<div style="background: #f00;width: 100px;height: 50px;float: right;">float1</div>
<div style="background: #00f;width: 100px;height: 50px;float: right;">float2</div>

效果:

注:如果父元素想包含float的子元素,可以触发父元素的BFC

推荐阅读