Skip to main content
Version: 1.2.0

Class Specificity

Styled-components is being used internally for styling in K2. If you apply a global class together with a K2 component class, the result might not be what you're expecting. If a property is defined in both classes with the same specificity, the last one will win.

Problem

In the following example, the K2 component class takes precedence over the global class since styled-components inject its styles during runtime at the end of the <head> by default. Thus its styles win over other single classname selectors.

<Card // has default white background
width="300px"
height="200px"
>
<div style={{ height: "100%" }} />
</Card>
// my-component.css
.card-root {
background-color: red;
}
// For some reason this component still has a white background,
// even though you're trying to override it with the "card-root" class!
<Card
width="300px"
height="200px"
classes={{
root: "card-root",
}}
>
<div style={{ height: "100%" }} />
</Card>

Solution

One solution is to bump up the specificity of the selectors in your stylesheet. Now, global CSS will override the default styles. For more details visit the official doc on Issues with specificity.

/* my-component.css */
.card-root.card-root {
background-color: red; // card has red background.
}