How do I make a class take precedence over an id?

后端 未结 5 1142
暖寄归人
暖寄归人 2020-12-25 15:17

But this doesn\'t work! The blah\'s width till cancels out class \"wider\"\'s with.

5条回答
  •  鱼传尺愫
    2020-12-25 16:16

    What you have there is a CSS specificity problem.

    .wider has a specificity of 0,0,1,0 while #normal has 0,1,0,0. You can't beat an ID with anything else than an ID (or inline definitions, but that is not the case here).

    What I would recommend, if you cannot put the needed width declaration in the #normal selector, is to put it in #normal.wider or, if that either isn't possible, have an identified container, say #container, as high in the hierarchy as possible (maybe an ID on the body?) and replace .wider with #container .wider. This new selector will have a specificity of 0,1,1,0 which is a bit higher than 0,1,0,0.

    Using !important will work too, but it should be used only as a last resort.

    Example:

    For this HTML snippet some possible selectors in decreasing order of specificity would be:

    CSS Selector         -> Specificity
    ---------------------------------------
    #container #normal   -> 0,2,0,0
    #container .wider    -> 0,1,1,0 // These two have the same specificity so
    #normal.wider        -> 0,1,1,0 // the last declared value will be used
    #normal              -> 0,1,0,0
    .wrapper .wider      -> 0,0,2,0
    .wider               -> 0,0,1,0
    

提交回复
热议问题