一、CSS Module
Modules 不是官方规范或浏览器中的实现,而是构建步骤中的一个过程(在 Webpack 或 Browserify 的帮助下),它改变了类名和选择器的作用域(即有点像命名空间)
目的:解决 CSS 中全局作用域的问题
二、开启 CSS Module
在 React 中默认开启了 CSS Module,样式表文件需要以 xxx.module.sass/less/css
命名。
三、作用域
默认 Less 或者 CSS 的规则是全局生效的,任何一个组件,只要有同名的 className 就会共用样式
CSS Module 可以有效避免作用域问题,它会生成一个唯一的标识作为 className
四、全局作用域(:global)
想要修改第三方组件样式,默认情况通过 css-module
无法修改,需要添加 :global
才可以
.login {
height: 100vh;
background: url(/https/blog.csdn.net/imgs/login_bg.jpeg) no-repeat;
background-size: cover;
background-position: center;
:global(.title) {
font-size: 42px;
line-height: 1.5;
text-align: center;
margin-bottom: 30px;
}
:global(.ant-btn-primary) {
background-color: red;
}
}
五、应用
import styles from './index.module.less';
export default function Login() {
return (
<div className={styles.login}>
<div className={styles.loginWrapper}>
<div className={styles.title}>系统登录</div>
<Form name='basic' initialValues={{ remember: true }} onFinish={onFinish} autoComplete='off'>
<Form.Item<FieldType> name='username' rules={[{ required: true, message: 'Please input your username!' }]}>
<Input />
</Form.Item>
<Form.Item<FieldType> name='password' rules={[{ required: true, message: 'Please input your password!' }]}>
<Input.Password />
</Form.Item>
<Form.Item>
<Button type='primary' htmlType='submit' block>
登录
</Button>
</Form.Item>
</Form>
</div>
</div>
);
}
- index.module.less
.login {
height: 100vh;
position: relative;
display: flex;
// background: url(/https/blog.csdn.net/img/login_bg.jpeg) no-repeat;
// background-size: cover;
// background-position: center;
background-color: #fff;
align-items: center;
justify-content: center;
.title {
font-size: 32px;
line-height: 1.5;
text-align: center;
margin-bottom: 30px;
}
.loginWrapper {
width: 500px;
}
}
css文件名以module命名之后就会生成唯一的className名,效果图如下: