出处:掘金
原作者:前端微白
最基础的样式隔离方案,通过严格的命名规则避免冲突:
<div class="card">
<button class="card__btn card__btn--primary">提交</button>
</div>
<style>
/* BEM 方法 */
.card__btn {
padding: 8px 16px;
border-radius: 4px;
}
.card__btn--primary {
background: #3498db;
color: white;
}
</style>
核心特点:
块(Block)__元素(Element)--修饰符(Modifier)import styles from './Button.module.css';
function Button() {
return (
<button className={styles.primary}>
Click me
</button>
);
}
/* Button.module.css */
.primary {
background: #3498db;
color: white;
}
/* 编译后生成:.Button_primary__d4f2a */
原理:编译构建时自动重命名类选择器,实现自动隔离
优势:
// SCSS方式实现隔离
.widget {
// 只在 .widget 内部应用
button {
background: #3498db;
color: white;
&:hover {
background: #2980b9;
}
}
}
编译后输出:
.widget button {
background: #3498db;
color: white;
}
.widget button:hover {
background: #2980b9;
}
适用场景:
// 使用 styled-components 实现隔离
import styled from 'styled-components';
const StyledButton = styled.button`
background: ${props => props.primary ? '#3498db' : '#e0e0e0'};
color: ${props => props.primary ? 'white' : 'black'};
/* 其他样式 */
`;
// 使用
<StyledButton primary>提交</StyledButton>
核心特性:
流行库:styled-components, Emotion, JSS
<template>
<button class="btn">点我</button>
</template>
<style scoped>
.btn {
background: #3498db;
color: white;
}
</style>
输出效果:
<button class="btn" data-v-497f297a>点我</button>
<style>
.btn[data-v-497f297a] {
background: #3498db;
color: white;
}
</style>
原理:添加组件唯一属性选择器实现样式隔离
<template id="user-card">
<style>
button {
background: #3498db;
color: white;
}
</style>
<button>点我</button>
</template>
<script>
class UserCard extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
const template = document.getElementById('user-card');
shadow.appendChild(template.content.cloneNode(true));
}
}
customElements.define('user-card', UserCard);
</script>
特点:
.isolated-component {
contain: style layout paint;
}
作用:
style:限制样式影响范围layout:独立布局上下文paint:独立绘制区域size:独立尺寸计算
此功能仍在发展中,请勿在生产环境使用,但代表未来方向
<!DOCTYPE html>
<html>
<head>
<style>
iframe {
border: 2px solid #3498db;
border-radius: 8px;
}
</style>
</head>
<body>
<h2>主应用区域</h2>
<!-- 完全隔离的微前端应用 -->
<iframe
src="widget.html"
title="隔离组件"
width="400"
height="300"
></iframe>
</body>
</html>
特点:
| 技术 | 隔离级别 | 学习曲线 | 性能影响 | 适用场景 |
|---|---|---|---|---|
| 命名约定 | 低 | 低 | 无 | 小型项目 |
| CSS Modules | 高 | 中 | 低 | React/Vue 组件库 |
| 预处理器嵌套规则 | 低 | 中 | 无 | 传统项目 |
| CSS-in-JS | 非常高 | 中高 | 中 | 动态主题应用 |
| Vue scoped | 高 | 低 | 低 | Vue.js 项目 |
| Shadow DOM | 完全隔离 | 高 | 低 | Web 组件 |
| CSS Containment | 中高 | 高 | 无 | 未来 Web 应用 |
| Iframe | 完全隔离 | 低 | 高 | 第三方插件/微前端应用 |
扩展资源: