CSS浮动合理利用可以带给我们很好的布局体验,但在很多时候因为元素的浮动似乎又给我们带来了很多麻烦。下面我们就来对神奇的浮动一探究竟。

  浮动是相对于CSS中的相对定位和绝对定位而言的,浮动的框可以向左向右移动,直到它的外边缘碰到保护框或另一个浮动框为止。由于浮动框不在文档的普通流中,所以文档的普通流中的块框表现得就像浮动框不存在一样。如果包含框太窄,无法容纳水平排列的几个浮动元素,那么空间不足的浮动框会向下移动,直到有足够的空间。如下图左边的图片。大家可能会想,如果浮动元素的高度不同怎么办?如下图右所示~这种情况下框3没有办法继续下移,所以只能卡在那里了~

如何更好利用浮动---浮动的合理利用及清除

  关于CSS浮动,float可谓功不可没。我们通过float属性实现元素的浮动,几乎所有浏览器都支持,属性值包括left(元素向左浮动)right(元素向右浮动)none(默认值,元素不浮动,并会显示在其文本中出现的位置)inherit(规定应该从父元素继承float属性的值)*低版本的IE不支持inherit属性,不过IE11支持。刚才测试中竟然发现IE不支持png的图片格式,各种sad~

  在低版本的IE中,float:right的元素会换行显示,需要把该元素写在同行元素的左边,在IE11中,就不必考虑那么多了,float:right不论写在一行的哪里都是可以的。

float的具体应用:

1可以使图像浮动于一个段落的右侧

 1 <html>
 2 <head>
 3 <style type="text/css">
 4 img 
 5 {
 6 float:right
 7 }
 8 </style>
 9 </head>
10 
11 <body>
12 <p>在下面的段落中,我们添加了一个样式为 <b>float:right</b> 的图像。结果是这个图像会浮动到段落的右侧。</p>
13 <p>
14 <img src="/i/eg_cute.gif" />
15 This is some text. This is some text. This is some text.
16 This is some text. This is some text. This is some text.
17 This is some text. This is some text. This is some text.
18 This is some text. This is some text. This is some text.
19 This is some text. This is some text. This is some text.
20 This is some text. This is some text. This is some text.
21 This is some text. This is some text. This is some text.
22 This is some text. This is some text. This is some text.
23 This is some text. This is some text. This is some text.
24 This is some text. This is some text. This is some text.
25 </p>
26 </body>
27 
28 </html>
View Code

相关文章: