层叠图层允许你将CSS组织成具有特定优先级的"图层",让你更好地控制层叠规则,使复杂的样式表更易于管理。
本章概述
层叠图层是CSS中一个革命性的特性,它解决了传统CSS中特异性管理困难的问题。通过将样式组织成不同的图层,我们可以明确控制样式的优先级,而不必依赖复杂的特异性计算或使用!important。
学习目标
理解层叠图层的基本概念和工作原理
掌握图层的定义和使用语法
学会图层优先级的控制方法
了解图层在大型项目中的应用
掌握图层的最佳实践和设计模式
层叠图层基础
基本语法
层叠图层使用@layer规则来定义和使用:
/* 定义图层 */ @layer base { h1 { font-size: 2rem; } } @layer components { .button { padding: 0.5rem 1rem; } }图层优先级
图层的优先级由声明顺序决定,后声明的图层优先级更高:
/* 定义图层顺序 */ @layer reset, base, theme, components, utilities; /* reset 图层 - 最低优先级 */ @layer reset { * { margin: 0; padding: 0; box-sizing: border-box; } } /* utilities 图层 - 最高优先级 */ @layer utilities { .text-center { text-align: center; } }基础应用示例
完整的图层系统
/* 1. 首先定义所有图层的顺序 */ @layer reset, base, theme, layout, components, utilities; /* 2. Reset 图层 - 重置默认样式 */ @layer reset { /* 重置所有元素的默认样式 */ *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; } /* 重置表单元素 */ button, input, select, textarea { font: inherit; color: inherit; } button { background: none; border: none; cursor: pointer; } /* 重置列表样式 */ ul, ol { list-style: none; } /* 重置链接样式 */ a { text-decoration: none; color: inherit; } } /* 3. Base 图层 - 基础样式 */ @layer base { /* 根元素样式 */ :root { --font-family-sans: system-ui, -apple-system, sans-serif; --font-family-mono: 'Monaco', 'Menlo', monospace; --line-height-base: 1.6; --line-height-tight: 1.2; } /* 基础排版 */ body { font-family: var(--font-family-sans); line-height: var(--line-height-base); color: #333; background-color: #fff; } /* 标题样式 */ h1, h2, h3, h4, h5, h6 { line-height: var(--line-height-tight); font-weight: 600; margin-bottom: 0.5em; } h1 { font-size: 2.5rem; } h2 { font-size: 2rem; } h3 { font-size: 1.75rem; } h4 { font-size: 1.5rem; } h5 { font-size: 1.25rem; } h6 { font-size: 1rem; } /* 段落样式 */ p { margin-bottom: 1rem; } /* 基础表单样式 */ input, textarea, select { padding: 0.5rem; border: 1px solid #ccc; border-radius: 4px; }