How does a CSS rule override another CSS rule?

后端 未结 4 572
无人共我
无人共我 2020-12-05 16:20

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;
h         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 16:50

    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, classes 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.

提交回复
热议问题