css权重简单之谈
时间:2010-12-02 来源:Jikey
在回答别人问题时,对自己真是一个考验提高,在总结,摸清原有模糊概念的基础上要讲,全,简,易。真是不容易。佩服那些写教程福利芸芸众生的先行者们~!!
下面简单谈谈css的权重:
内嵌样式 > 内部样式表 > 外联样式表
如:
<head>
<link href="main.css" rel="stylesheet" type="text/css" />
<style>
.txt{color:blue;}
</style>
</head>
<p class="txt" style="color:red">这是一个测试文本</p> main.css中: .txt{color:green} 这三个里边:
内嵌样式:
style="color:red" 内部样式表:<style>
.txt{color:blue;}
</style>
外联样式表:
中内容。
这是大体上的css权重量级别,一般常用外联。
然后我们在看常用的main.css中权重级别:
在main.css 中:
id选择器的权重是大于类选择器的权重。
如:
#test{color:red;}
.test{color:blue;} 其中#test的大于.test的权重。
另外如果在一个css文件中出现两个同命的css属性值,那会怎么样呢?当然跟其它面向对象程序语言中的,覆盖相似,下面的属性会覆盖掉上面的属性。如:
.test2{color:red;border:1px solid #ccc;}
.test2{color:blue;font-size:14px;} 这样最终应用到DOM元素上的样式是:
color:blue;font-size:14px;border:1px solid #ccc; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>豪情</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <style type="text/css"> *{margin:0;padding:0;font-size:12px;} .test2{color:red;border:1px solid #ccc;} .test2{color:blue;font-size:14px;} </style> </head> <body> <div class="test2">这是一个test2的内容</div> </body> </html>
运行代码
还有一种情况是层次选择器下面权重的延伸,这种情况是用js操作动态效果时可以节省不少js代码,在逻辑上面来说,展现与行为的分离也是尽善尽美。
.txt{color:blue;}
#wrap .txt{color:red;font-size:14px;} 如:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>豪情</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <style type="text/css"> *{margin:0;padding:0;font-size:12px;} .txt{color:blue;} #wrap .txt{color:red;font-size:14px;} </style> <head> <body> <div class="txt">这是一个txt文本</div> <div id="wrap"> <div class="txt">这又是一个txt文本</div> </div> </body> </html>
运行代码
相关阅读 更多 +