How does a CSS rule override another CSS rule?

后端 未结 4 515
无人共我
无人共我 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:44

    This has to do with specificity. table#id-form td is more specific than #particular-td. A rule with higher specificity has precedence over a rule with lower specificity.

    Here are a few resources to get you started on understanding how it works:

    • Smashing Magazine article
    • W3C spec on specificity
    • Specificity calculator

    About using !important, as suggested by others:

    One might be tempted to use the !important keyword to sort this out, but that is rarely a good idea:

    1. It becomes a pain to maintain/troubleshoot
    2. It breaks the normal flow of CSS
    3. The rule cannot be overridden by other rules later on

    It might take a few minutes to read up on specificity, but it will be well worth the time spent when you've got a grasp of it.

    0 讨论(0)
  • 2020-12-05 16:44

    You have two ways, either add !important after your padding for the particular-td:

    padding: 10px !important;
    

    OR, your selector altered like so:

    table#id-form td#particular-td {
    border: 1px solid black;
    text-align: center;
    background-color: #DFDFDF;
    height: 30px;
    padding: 10px;
    }
    

    Both are fine. Personally I don't like the use of !important if I can avoid it.

    0 讨论(0)
  • 2020-12-05 16:46

    Try this code, I have added !important to your css, in this mode can ovveride padding of table#id-form td

    #particular-td {
    border: 1px solid black;
    text-align: center;
    background-color: #DFDFDF;
    height: 30px;
    padding: 10px !important;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题