CSS规则如何覆盖另一个CSS规则? [英] How does a CSS rule override another CSS rule?
问题描述
所以,这是我在做什么:
#id-form td {
padding:0 0 10px 0;
}
#special-td {
border:1px solid black;
text-align:center;
background-color:#DFDFDF;
height:30px;
padding:10px;
}
我有一个表#id-form
,其中我设置所有
td
s有 padding-bottom:10px
。
但是在一个特殊的场合,我想要一个特殊的 td
在所有方向都有 padding:10px
我在#specific-td
中设置。
显然,我把CSS样式顺序放在外部文件。
但是渲染的CSS只有 padding-bottom
,并且出现 padding:10px
如何以及为什么会发生这种情况? >
我应该如何安排这些规则来解决我的问题(除了内联样式)?
删除表中#id-form
之前的'table'
因为CSS特异性。选择器的权重是基于组成它的组件来评估的, id
'的加权为100, class
es的权重为10,元素
的权重为1的选择器。
/ p>
table#id-form td
加权为102( table#id
为101, td
为1) ,而此:
#special-td
具有100的权重。如果您将第二个更改为:
id-form#specific-td
您将获得200的权重,将覆盖上一个选择器。只有作为最后的手段,你应该使用!important
,因为这很大程度上阻止你进一步下去。
So, this is what I'm doing:
#id-form td {
padding: 0 0 10px 0;
}
#particular-td {
border: 1px solid black;
text-align: center;
background-color: #DFDFDF;
height: 30px;
padding: 10px;
}
I have a table #id-form
, on which I set all td
s to have padding-bottom: 10px
.
But on one special occasion, I want a particular td
to have padding: 10px
in all directions, which I set in the #particular-td
.
Obviously, I put the CSS styling in sequence in an external file.
But the rendered CSS only has padding-bottom
, and padding: 10px
appears to be overridden!?
Please explain:
How and why is this happening?
How should I arrange these rules to solve my problem (other than inline styling)?
EDIT: I removed 'table'
before #id-form
in table. I was never using this, I just mentioned it here to be able to explain it better.
Because of CSS Specificity. A selector's weighting is evaluated based on the components that make it up, with id
's given a weighting of 100, class
es with a weighting of 10, and element
selectors with weighting of 1.
So in your example:
table#id-form td
Has a weighting of 102 (table#id
is 101 and td
is 1), whereas this:
#particular-td
Has a weighting of 100. If you change your second to this:
#id-form #particular-td
You will get a weighting of 200 which will override the previous selector. Only as a last resort should you ever use !important
, as this pretty much prevents you from overriding it further down the line.
这篇关于CSS规则如何覆盖另一个CSS规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!