float属性可以让元素脱离文档流,父元素中的子元素设置为float,则会导致父元素的高度塌陷。
<style type="text/css">
.father{ /*没有给父元素定义高度*/background:#ccc; border:1px dashed #999;
}
.box01,.box02,.box03{ height:50px; line-height:50px; background:#f9c; border:1px dashed #999; margin:15px; padding:0px 10px;float:left; /*定义box01、box02、box03三个盒子左浮动*/
}
</style>
</head>
<body>
<div class="father"><div class="box01">box01</div><div class="box02">box02</div><div class="box03">box03</div>
</div>
</body>
</html>
因为浮动元素脱离文档流,为了撑起父元素,通常可以在父元素内再增加一个块元素。
.box04{height: 100px;border-style: solid;
}
</style>
</head>
<body>
<div class="father"><div class="box01">box01</div><div class="box02">box02</div><div class="box03">box03</div><div class="box04">box04</div>
</div>
父元素的高度取决于box04的高度,则必须知道浮动元素的高度,并以此值来指定了box04的高度,显然不方便。
为解决此问题,可将box04设置清除浮动属性。清除浮动的意思是指,元素在左右不允许有浮动元素,如果左右存在浮动元素,元素自己就下移(不是将浮动元素下移)。
当clear属性设置为left,表示元素之前如果有左浮动元素,则元素本身下移到浮动元素之后。
.box04{ width: 100px;border-style: solid; clear:left;
}
</style>
</head>
<body>
<div class="father"><div class="box01">box01</div><div class="box02">box02</div><div class="box03">box03</div><div class="box04">a</div>
</div>
效果如下:
将box04的边框和文字隐去
.box04{ clear:left;
}
</style>
</head>
<body>
<div class="father"><div class="box01">box01</div><div class="box02">box02</div><div class="box03">box03</div><div class="box04"></div>
</div>
达到将父框撑起的效果,而且父框能够自动适合浮动框大小。