防止样式污染的一些方法

120 阅读1分钟

Vue的Scoped

实现原理

每个组件增加一个唯一的自定义属性,再通过属性选择器实现作用域隔离样式的效果

image.png

css Modules

实现原理:

css-loader 将 CSS 类名转换为局部作用域的标识符,从而避免全局命名冲突。

在构建过程中,css-loader 会为每个 CSS 类名生成一个唯一的标识符。这个标识符通常是一个哈希值,它基于类名和文件路径生成。这样,即使不同组件中使用了相同的类名,它们在最终生成的 CSS 文件中也会有不同的标识符,从而避免了命名冲突。

cra.nodejs.cn/docs/adding…

import styles from './100-styles.module.css';

export default function App() {
    return (
        <div className={styles.app}>
            <div className={styles.left}>left</div>
            <div className={styles.right}>
                <div className={styles.header}>header</div>
                <div className={styles.content}>content</div>
                <div className={styles.footer}>footer</div>
            </div>
        </div>
    )
}

100-styles.module.css 文件

.app {
    display: flex;
    flex-direction: row;
}
.left {
    width: 20vw;
    height: 100vh;
    background-color: aquamarine;
}
.right {
    width: 80vw;
    height: 100vh;
    background-color: bisque;
}
.header {
  background-color: green;
  padding: 20px;
  width: 100%;
  height: 20vh;
}

.content {
  background-color: blue;
  padding: 20px;
  width: 100%;
  height: 40vh;
}

.footer {
  background-color: red;
  padding: 20px;
  width: 100%;
  height: 20vh;
}

最后页面生成: image.png

扩展:className添加多个类名、添加全局类名

实现代码:

image.png

image.png

image.png

image.png 最后页面生成:

image.png

BEM规范

遵循BEM命名规范getbem.com/naming/

影子 DOM(Shadow DOM)

参考

juejin.cn/post/718582…