对css中clear元素的理解

  clear:left;表示左侧不能有浮动元素。

  clear:right;表示右侧不能有浮动元素。
  clear:both;表示左右两侧都不能有浮动元素。

  但在使用时,还得考虑css优先级问题。相同类型选择器制定的样式,在样式表文件中,越靠后的优先级越高 。

  当所有元素的clear属性都设为right时,由于优先级的原因,并不是所想的那样:右侧没有浮动元素,而是右侧出现了浮动元素。

  比如下面的代码:

  
<html>
<head>
<style type="text/css">

.div1
{
height:40px;
width:40px;
background-color:red;
position:releative;
float:left;
clear:right;
}
.div2
{
height:40px;
width:40px;
background-color:green;
position:relative;
float:left;
clear:right;
}
.div3
{
height:40px;
width:40px;
background-color:yellow;
position:relative;
float:left;
clear:right;
}
.div4
{
height:40px;
width:40px;
background-color:black;
position:relative;
float:left;
clear:right;
}
.div5
{
height:40px;
width:40px;
background-color:blue;
position:relative;
float:left;
clear:right;
}
</style>
</head>

<body>
<div class="div1">
</div>
<div class="div2">
</div>
<div class="div3">
</div>
<div class="div4">
</div>
<div class="div5">
</div>
</body>

</html>
clear-right

  其中:class优先级关系: div5>div4>div3>div2>div1 

  所以,呈现出下图情况:

  

 

  当所有元素的clear属性都设为left时,由于优先级的原因,并不是所想的那样:右侧可以有浮动元素,而是右侧不能出现浮动元素。

  比如下面的代码:

<html>
<head>
<style type="text/css">

.div1
{
height:40px;
width:40px;
background-color:red;
position:releative;
float:left;
clear:left;
}
.div2
{
height:40px;
width:40px;
background-color:green;
position:relative;
float:left;
clear:left;
}
.div3
{
height:40px;
width:40px;
background-color:yellow;
position:relative;
float:left;
clear:left;
}
.div4
{
height:40px;
width:40px;
background-color:black;
position:relative;
float:left;
clear:left;
}
.div5
{
height:40px;
width:40px;
background-color:blue;
position:relative;
float:left;
clear:left;
}
</style>
</head>

<body>
<div class="div1">
</div>
<div class="div2">
</div>
<div class="div3">
</div>
<div class="div4">
</div>
<div class="div5">
</div>
</body>

</html>
clear-left

  其中:class优先级关系: div5>div4>div3>div2>div1 。 

  所以,呈现出下图情况:

  我有时偶尔还是会绕晕。。反正,了解了css优先级问题,就容易理解了。

posted @ 2016-11-06 21:33  京魂  阅读(1461)  评论(0编辑  收藏  举报