float是什么?
float即为浮动,在CSS中的作用是使元素脱离正常的文档流并使其移动到其父元素的“最左边”或“最右边”。下面解释下这个定义中的几个名词的概念:
文档流:在html中文档流即为元素从上至下排列的顺序。
脱离文档流:元素从正常的排列顺序被抽离。
最左边/最右边:上述的移动到父元素最左和最右是指元素往左或往右移动直到碰到另一个浮动元素或父元素内容区的边界(不包括padding)。
为啥要有float?
思考这么一个问题,如何实现图片环绕文字?position属性可以做到么?
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<p>在下面的段落中,我们添加了一个样式为 <b>float:right</b> 的图像。结果是这个图像会浮动到段落的右侧。</p>
<p>
![](http://upload.jianshu.io/users/upload_avatars/33455/c48074816072?imageMogr2/auto-orient/strip|imageView2/1/w/240/h/240)
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>
上述代码的结果是
如果给style加这么一句
<style type="text/css">
img{
float:left;
}
</style>
结果是
也就是说float实现了文本环绕图像的功能。
更复杂的例子参考
W3School在线测试工具 V2
实现首字母大写
<html>
<head>
<style type="text/css">
div
{
float:left;
font-size:500%;
font-family:algerian,courier;
line-height:50%;
}
</style>
</head>
<body>
<div>T</div>
<p>
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>
<p>
在上面的段落中,文本的第一个字母包含在一个 span 元素中。这个 span 元素的宽度是当前字体尺寸的 0.7 倍。span 元素的字体尺寸是 400%,行高是 80%。span 中的字母字体是 "Algerian"
</p>
</body>
</html>
结果如图
当然还有其他方法
CSS实现段落首字母、首字放大特效CSS教程CSS网页制作脚本之家