CSS Deprecate single class when there are 2 classes

前端 未结 2 1758
旧巷少年郎
旧巷少年郎 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: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 */ }
    

提交回复
热议问题