来源:自学PHP网 时间:2018-02-08 10:48 作者: 阅读:次
[导读] CSS clear 属性用于清除元素的浮动。clear属性指定元素是紧挨着它前面的浮动元素,还是移动到浮动元素的下方(元素被清除了浮动)。...
|
CSS clear 属性用于清除元素的浮动。clear属性指定元素是紧挨着它前面的浮动元素,还是移动到浮动元素的下方(元素被清除了浮动)。
当 例如下图中,ABC三个元素都左浮动,它们会排列为一排,如左边图像所示。如果我们将第二个元素的左浮动清除,第二个元素就会被移动到第一个元素的下方。注意第三个浮动元素,它的位置也会被改变。
如果一个容器中只有一个子元素,而这个子元素被设置了浮动,容器本身没有设置浮动,并且没有设置高度的时候,容器就会“坍塌”,如果下图A图所示。
<div class="box">
<img src="1.jpg" class="thumb">
</div>
/* css样式 */
.box{
width: 300px;
padding: 10px;
border: 2px solid #66677c;
}
img.thumb{
width: 270px;
float: left;
}
解决的方法有2个:1、使父容器也浮动起来。
.box{
float: left;
width: 300px;
padding: 10px;
border: 2px solid #66677c;
}
2、添加一个额外的空块级元素,为这个元素设置清除浮动属性,使它“撑开”容器。
<div class="box">
<img src="1.jpg" class="thumb">
<div class="clear"></div>
</div>
/* css样式 */
.box{
width: 300px;
padding: 10px;
border: 2px solid #66677c;
}
img.thumb{
width: 270px;
float: left;
}
.clear: both;
如果不想添加额外的元素,可以直接使用
.box:after{
content: ' ';
display: block;
clear: both;
}
官方语法
clear: none | left | right | both | inherit
参数:
应用范围
示例代码下面是一个清除浮动的经典代码,详细代码介绍可以参考:。这段代码兼容Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+浏览器。代码如下:
/**
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* contenteditable attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that are clearfixed.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.cf:before,
.cf:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.cf:after {
clear: both;
}
/**
* For IE 6/7 only
* Include this rule to trigger hasLayout and contain floats.
*/
.cf {
*zoom: 1;
}
在线演示DEMO1:下面的例子演示了元素清除浮动之前和清除浮动之后的情况。 没有清除浮动:清除浮动之后:
浏览器支持所有的现代浏览器都支持 |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com