详解CSS中clear:left/right的用法
详解CSS中clear:left/right的用法
在CSS中,clear属性常被用来清除浮动(float)带来的影响,以保证元素在文档中被正常显示。在清理浮动的时候,clear属性可以被设置为left、right或both,表示清除左浮动、右浮动或两侧浮动带来的影响。
语法
.clear{
clear: left | right | both;
}
值
left: 表示清除左侧浮动对元素的影响right: 表示清除右侧浮动对元素的影响both: 表示清除左右侧浮动对元素的影响
示例说明
示例1
在下面的示例中,我们为.box元素设置了一个左浮动,.clear元素为了避免被.box元素的浮动影响,将clear属性设置为left,从而保证.clear元素在.box元素的下方显示。
<div class="container">
<div class="box"></div>
<div class="clear"></div>
</div>
.box {
float: left;
width: 200px;
height: 200px;
background-color: red;
}
.clear {
clear: left;
height: 100px;
background-color: blue;
}
示例2
另一个示例中,我们为.left和.right元素分别设置了左浮动和右浮动,并且我们希望.bottom元素在.left元素的下方显示。由于clear: left无法清除.right元素的右浮动,因此我们需要为.bottom元素设置clear: both,以清除.left和.right元素的浮动影响。
<div class="container">
<div class="left"></div>
<div class="right"></div>
<div class="bottom"></div>
</div>
.left {
float: left;
width: 150px;
height: 150px;
background-color: red;
}
.right {
float: right;
width: 150px;
height: 150px;
background-color: green;
}
.bottom {
clear: both;
height: 100px;
background-color: blue;
}
以上就是关于clear属性的详细讲解和示例,希望能够对你理解clear属性在清除浮动时的用法有所帮助。
