Search code examples
cssreactjscss-modules

CSS styling precedence when using React and CSS modules


I have a css module which apply styling to an existing component. The css module works fine but the styling was always overwritten by the default style of component.

Supposed I have this markup.

 <Header className={styles.header}>
      <Row type="flex" justify="space-between">
        <Col>
          <Link to="/">
            <Title className={styles.brand}>Shiritori</Title>
          </Link>
        </Col>
      </Row>
 </Header>

Then uses the styles declare in the css module:

.header {
  background: rgb(75, 191, 107);
  margin-bottom: 1rem;

  > div {
    align-items: center;
  }
}

I expect that the background css property of the default style will be overwritten but instead the styles in my css module was canceled out.

Actual result:

.ant-layout-header {
    height: 64px;
    padding: 0 50px;
    line-height: 64px;
    background: #001529;
}
.ant-layout-header, .ant-layout-footer {
    -ms-flex: 0 0 auto;
    flex: 0 0 auto;
}
.ant-layout, .ant-layout * {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
.App_header__37gyT {
    background: #4bbf6b; <- this property was overwritten by the .ant-layout-header background property
    margin-bottom: 1rem;
}   

I also consider the order of css/scss import but same result.

import "../../../node_modules/antd/dist/antd.css";
import styles from "./App.module.scss";

Is there a way to overwrite existing style of a component. I use antd for the UI toolkit and components.


Solution

  • Unable to replicate your issue. Seems to be working fine:

    Edit Ant-Design CSS Specifity

    That said, when dealing with CSS specificity, you can do one of several things:

    1. Overwrite a child class style from a parent class style.

    2. Use the id property: <Header id="header-id">Header</Header> (then use the # to refer to header: #header-id { ... })

    3. Overwrite the .ant-layout class name within a separate CSS/SCSS file.

    4. Add an !important declaration after the style property, for example: background: pink !important;

    That said, I'd avoid importing the entire CSS library and instead use the babel plugin to import only what's needed.