float 指定一个元素是否可以浮动。(假如在一行之上只有极少的空间可供浮动元素,那么这个元素会跳至下一行,这个过程会持续到某一行拥有足够的空间为止。)
float:left 向左浮动
float:right 向右浮动
当块级元素设置了float属性后,不再只能独占一行,而是可以实现多个块级元素处于同一行。
常见的块级元素:<ul> <li> <p> <div> <h1>~<h6> <table> <form>等等。
没使用float:
<html>
<head>
<style>
#d1{width:120px;height:120px;background-color:red;}
#d2{width:120px;height:120px;background-color:green;}
#d3{width:120px;height:120px;background-color:blue;}
</style>
</head>
<body>
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
</body>
</html>
使用float:
<html>
<head>
<style>
#d1{width:120px;height:120px;background-color:red;float:left}
#d2{width:120px;height:120px;background-color:green;float:left}
#d3{width:120px;height:120px;background-color:blue;float:left}
</style>
</head>
<body>
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
</body>
</html>
当一个父元素中子元素全部是浮动的时,对于其父元素来说,元素浮动之后,它脱离当前正常的文档流,所以它无法撑开其父元素,造成父元素的塌陷。
<html>
<head>
<style>
#d0{background-color:yellow;}
#d1{width:120px;height:120px;background-color:red;float:left}
#d2{width:120px;height:120px;background-color:green;float:left}
#d3{width:120px;height:140px;background-color:blue;float:left}
</style>
</head>
<body>
<div id="d0">
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
</div>
</body>
</html>
通过clear:both解决这个问题:
<html>
<head>
<style>
#d0{background-color:yellow;}
#d1{width:120px;height:120px;background-color:red;float:left}
#d2{width:120px;height:120px;background-color:green;float:left}
#d3{width:120px;height:140px;background-color:blue;float:left}
</style>
</head>
<body>
<div id="d0">
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
<div style="clear:both"></div>
</div>
</body>
</html>
清除属性clear :设置一个元素的侧面是否允许其他的浮动元素。
none | left |right | both
参数:
none : 允许两边都可以有浮动对象
both : 不允许有浮动对象
left : 不允许左边有浮动对象
right : 不允许右边有浮动对象
小栗子:
红绿左浮动,蓝无清除浮动
<html>
<head>
<style>
#d1{width:120px;height:120px;background-color:red;float:left;}
#d2{width:120px;height:120px;background-color:green;float:left;}
#d3{width:120px;height:140px;background-color:blue;}
</style>
</head>
<body>
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
</body>
</html>
红绿左浮动,蓝清除浮动:
<html>
<head>
<style>
#d1{width:120px;height:120px;background-color:red;float:left;}
#d2{width:120px;height:120px;background-color:green;float:left;}
#d3{width:120px;height:140px;background-color:blue;clear:both}
</style>
</head>
<body>
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
</body>
</html>
理解还不深,,,探究完善中。。。