CSS Deprecate single class when there are 2 classes

前端 未结 2 1720
旧巷少年郎
旧巷少年郎 2021-01-23 22:02

There is a div, and it has 2 class names.

like -

What I want is that if there are .A.B {}, the it will deprec

相关标签:
2条回答
  • 2021-01-23 22:46

    In css whatever comes last takes precedence - that is why it is called a cascading style sheet. The exceptions to this are if the !important flag is used or if the previous selector is more specific than the latter. In your case .A.B{} is more specific and so it will automatically override any of the same attributes in .A{} and .B{}. If you want an attribute in .B{} to override an attribute in .B{} or vice versa you just need to make sure it comes last.

    0 讨论(0)
  • 2021-01-23 22:55

    If an element has class A, then it has class A, and you can't "turn that off" by adding another class B. But I can think of three approaches:

    "Normal" approach

    Define properties in an .A.B rule that override the properties in the .A or .B rules.

    .A   { color: blue;  }
    .B   { color: green; }
    .A.B { color: red;   }
    

    Or, if you want to "undo" the individual .A and .B rules when both classes are present, then:

    .A.B { color: initial; }
    

    initial is a special value which means, basically, the default value, or the inherited value for inherited properties.

    Using all

    There is an all shorthand property which refers to all CSS properties. You should probably not use this, because it's sort of a sledgehammer,

    .A.B { all: initial; }
    

    This will reset all properties on .A.B elements, including ones that were specified in individual .A and .B rules, to their initial values. Other values for the all property include inherit and unset. See the documentation for details.

    Using :not

    Another possibility is to rewrite your A and B rules to exclude the case where both are specified together, by using :not. However, this is also a bit of a blunt knife that you may cut yourself with, and it won't scale that well to more classes.

    .A:not(.B) { /* rules for A by itself */  }
    .B:not(.A) { /* rules for B by itself */  }
    .A.B       { /* rules for both A and B */ }
    
    0 讨论(0)
提交回复
热议问题