浮动
浮动就是将元素从常规文档流中拿出来。
1 . 浮动的作用
(1)实现传统出版物那样文字绕排图片的效果。
(2)让原来上下堆叠的块级元素,变成左右并列,从而实现分栏
当你浮动一个元素的时候,就好像在说:尽量把这个元素往上放,能放多高放多高,直到碰到某个元素的边界为止——它父元素的内边界(整个border的中间),就算是这样也不包含在父元素之内了。
注意:浮动非图片元素的时候,必须给它设定宽度,否则后果难以预料,但图片的话,为了使得它的宽度能满足我们的要求,建议使用width、height来设定它的大小
2 . 使用
- 文件绕排图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
/*body{margin:0;padding: 0;}*/
p{
margin: 0 0 10px 0;
border:1px solid blue;
}
img{
float: left;
margin:0 5px;
width:50px;
height: 80px;
}
footer{
border:1px solid red;
}
</style>
</head>
<body>
<img src="img/1.png"/>
<p>jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
</p>
<footer>
Query has changed the way that millions of people write JavaScript.
</footer>
</body>
</html>
结果:
- 创建分栏
<style>
p{
margin: 0 0 10px 0;
border:1px solid blue;
float: left;
width: 300px;
}
img{
float: left;
margin:0 5px;
width:50px;
height: 80px;
}
</style>
结果:
分栏原理:
这样同时浮动图片和“有宽度”段落,会导致段落的文本绕排效果消失,而浮动的段落也会尽可能向上移动,碰到图片这个盒子时不再向左。
换句话说:如果几个相邻的元素都具有设定的宽度,都是浮动的,而且水平控件也能容纳它们,它们就会并排在一行。
但是浮动的元素位于“文档外部”因而它已经不被包含在标记中的父元素之内,正因为如此,它对布局可能产生破坏性影响