CSS float浮动

什么是 CSS Float(浮动)

CSS 的 Float(浮动),会使元素向左或向右移动,其周围的元素也会重新排列。

Float(浮动),往往是用于图像,但它在布局时一样非常有用。



元素怎样浮动

元素的水平方向浮动,意味着元素只能左右移动而不能上下移动。

一个浮动元素会尽量向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止。

浮动元素之后的元素将围绕它。

浮动元素之前的元素将不会受到影响。

如果图像是右浮动,下面的文本流将环绕在它左边:

<html>
<head>
<style>
img
{
float:right;
}
</style>
</head>
<body>
<p>In the paragraph below, we have added an image with style <b>float:right</b>. The result is that the image will float to the right in the paragraph.</p>
<p>
<img src="/Public/images/logo.gif" width="160" height="60" />
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
</p>
</body>
</html>

效果:
css float效果



彼此相邻的浮动元素

如果你把几个浮动的元素放到一起,如果有空间的话,它们将彼此相邻。

在这里,我们对图片廊使用 float 属性:

<html>
<head>
<style>
.thumbnail
{
float:left;
width:110px;
height:90px;
margin:5px;
}
</style>
</head>

<body>
<h3>Image Gallery</h3>
<p>Try resizing the window to see what happens when the images does not have enough room.</p>
<img class="thumbnail" src="/Public/images/logo.gif" width="107" height="90">
<img class="thumbnail" src="/Public/images/logo.gif" width="107" height="80">
</body>
</html>


清除浮动 - 使用 clear

元素浮动之后,周围的元素会重新排列,为了避免这种情况,使用 clear 属性。

clear 属性指定元素两侧不能出现浮动元素。

使用 clear 属性往文本中添加图片廊:

.text_line{
clear:both;
}


CSS 中所有的浮动属性

"CSS" 列中的数字表示不同的 CSS 版本(CSS1 或 CSS2)定义了该属性。

属性 描述 CSS
clear 指定不允许元素周围有浮动元素。 left right both none inherit 1
float 指定一个盒子(元素)是否可以浮动。 left right none inherit 1