我们知道对于html中的样式文件, 我们可以把它放在 head标签里面。即使是同一个元素的样式,用同一个选择器定义也可以分段定义。
如:
selector{width:100px;}
selector{width:120px;}
以下html文件同时定义同一个元素的样式,用不同的选择器定义
<html>
<head>
<title>css.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
div{background:Yellow;}
.divCls2{background:Green;}
.divm{background:Gray;}
.divCls1{background:Purple;}
.divCls2{font-size:22px !important; }
.divCls2{font-size:40px;}
</style>
</head>
<body>
<div id="div" class="divm divCls1 divCls2" >
这是一次通过id class tag定义样式的分析
</div>
</body>
</html>
测试1
在各大浏览器上运行的效果如下图:
记住上述运行结果显示背景为灰色。
测试2
调整 样式清单如下
<style type="text/css">
.divm{background:Gray;}//!important div{background:Yellow;} </style> 运行结果仍然为灰色,图片如下#div{background:Red;}
所以不难分析 id 和类名选择器:id优先于类名(clsName)
当试图改换标div标签定义样式的位置
变化一:
<style type="text/css">
.divm{background:Gray;}//!importantdiv{background:Yellow;}
</style>
发现浏览器上显示的效果为灰色 ,即类名定义大于标签样式定义
变化二:
<style type="text/css"> div{background:Yellow;} .divCls2{background:Green;} .divm{background:Gray;} .divCls1{background:Purple;} </style>
结果显示为紫色(Purple),在div中给定class的属性值是divm divCls1 divClas2也就是说统统一元素的类名定义样式是由样式清单里的顺序决定的,而不是元素class属性值决定的,而且是后来居上,也就是元素的类名属性定义的样式,后定义的会覆盖先定义的,这与解释器的运行顺序一致
因此样式选择器定义元素样式总结如下:
id>clsName(类名 )>tag(标签名),同一元素类名在样式清单里后定义占主导
细心的读者可以发现样式里有个important的注释行
关于网上说的ie6对important不支持,这种说法是错误的。应该说ie6不是很好的支持这一特性。
怎么说呢,代码示例如下
selector{width:100px !important; width:200px;}
ie 将显示宽度为200px
如果写成这样
selector{width:100px !important; }
selector{ width:200px;}
ie 将显示宽度为100px
也就是说如果在同一个选择器内定义设置属性的值,那么在ie内important将失效,除非分开写