CSS 使用 React 和 CSS 模块时的样式优先级
CSS styling precedence when using React and CSS modules
我有一个 css 模块,可以将样式应用于现有组件。 css 模块工作正常,但样式总是被组件的默认样式覆盖。
假设我有这个标记。
<Header className={styles.header}>
<Row type="flex" justify="space-between">
<Col>
<Link to="/">
<Title className={styles.brand}>Shiritori</Title>
</Link>
</Col>
</Row>
</Header>
然后使用 css 模块中声明的样式:
.header {
background: rgb(75, 191, 107);
margin-bottom: 1rem;
> div {
align-items: center;
}
}
我预计默认样式的 background
css 属性 会被覆盖,但 css 模块中的样式被取消了。
实际结果:
.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;
}
我也考虑了 css/scss 导入的顺序,但结果相同。
import "../../../node_modules/antd/dist/antd.css";
import styles from "./App.module.scss";
有没有办法覆盖组件的现有样式。我将 antd 用于 UI 工具包和组件。
无法重现您的问题。似乎工作正常:
也就是说,在处理 CSS 特异性时,您可以执行以下操作之一:
从 parent class 样式覆盖 child class 样式。
用id
属性:<Header id="header-id">Header</Header>
(然后用#
指header:#header-id { ... }
)
在单独的 CSS/SCSS 文件中覆盖 .ant-layout
class 名称。
在样式属性之后添加一个!important
声明,例如:background: pink !important;
也就是说,我会避免导入整个 CSS 库,而是使用 babel plugin 仅导入需要的内容。
我有一个 css 模块,可以将样式应用于现有组件。 css 模块工作正常,但样式总是被组件的默认样式覆盖。
假设我有这个标记。
<Header className={styles.header}>
<Row type="flex" justify="space-between">
<Col>
<Link to="/">
<Title className={styles.brand}>Shiritori</Title>
</Link>
</Col>
</Row>
</Header>
然后使用 css 模块中声明的样式:
.header {
background: rgb(75, 191, 107);
margin-bottom: 1rem;
> div {
align-items: center;
}
}
我预计默认样式的 background
css 属性 会被覆盖,但 css 模块中的样式被取消了。
实际结果:
.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;
}
我也考虑了 css/scss 导入的顺序,但结果相同。
import "../../../node_modules/antd/dist/antd.css";
import styles from "./App.module.scss";
有没有办法覆盖组件的现有样式。我将 antd 用于 UI 工具包和组件。
无法重现您的问题。似乎工作正常:
也就是说,在处理 CSS 特异性时,您可以执行以下操作之一:
从 parent class 样式覆盖 child class 样式。
用
id
属性:<Header id="header-id">Header</Header>
(然后用#
指header:#header-id { ... }
)在单独的 CSS/SCSS 文件中覆盖
.ant-layout
class 名称。在样式属性之后添加一个
!important
声明,例如:background: pink !important;
也就是说,我会避免导入整个 CSS 库,而是使用 babel plugin 仅导入需要的内容。