Html CSS样式优先
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12088007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Css style priority
提问by Jargo
I am having problems with CSS declaration priority. My page contains an external CSS file with a rule and some inline CSS declarations, which are supposed to override that rule. To my understanding inline style declarations should override external CSS declarations. However, when I view the page in Chrome the second row of the table is displayed blue, when it should be displayed red as defined in the internal style declarations.
我在 CSS 声明优先级方面遇到了问题。我的页面包含一个带有规则和一些内联 CSS 声明的外部 CSS 文件,这些声明应该覆盖该规则。据我了解,内联样式声明应该覆盖外部 CSS 声明。但是,当我在 Chrome 中查看页面时,表格的第二行显示为蓝色,而应该按照内部样式声明中的定义显示为红色。
What am I missing here
我在这里错过了什么
Here is the HTML:
这是 HTML:
<html>
<head>
<link rel="stylesheet" href="screen.css" type="text/css" media="screen, projection">
<style type="text/css">
td,tr,th
{
background: Red;
}
</style>
</head>
<body>
<table>
<tr>
<td>11</td>
<td>22</td>
</tr>
<tr>
<td>aa</td>
<td>bb</td>
</tr>
</table>
</body>
</html>
Here is the content of the CSS file:
这是 CSS 文件的内容:
tbody tr:nth-child(even) td,
tbody tr.even td
{
background: #e5ecf9;
}
回答by andyb
The number of selectors matters when calculating which rule has the highest specificity.
在计算具有最高特异性的规则时,选择器的数量很重要。
Two excellent visualizations of CSS specificity are http://www.standardista.com/css3/css-specificity/and http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
CSS 特异性的两个优秀可视化是http://www.standardista.com/css3/css-specificity/和http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
You should avoid just sticking !important
on the rule to override (see What are the implications of using "!important" in CSS?) and instead change the selector to give your rule more or equal weight to the imported rule.
您应该避免只坚持!important
要覆盖的规则(请参阅在 CSS 中使用 "!important" 的含义是什么?),而是更改选择器以赋予您的规则更多或相等于导入规则的权重。
For example the following will make all cells background:red
例如以下将使所有单元格 background:red
thead tr:nth-child(1n) th, tbody tr:nth-child(1n) td {
background:red;
}
回答by Raisch
In this case the more detailed rule will get it.
在这种情况下,更详细的规则将得到它。
Try this in your HTML:
在你的 HTML 中试试这个:
<style type="text/css" media="screen, projection">
tbody tr:nth-child(even) td,
tbody tr:nth-child(even) tr,
tbody tr:nth-child(even) th
{
background: Red;
}
</style>
Best regards
此致