样式表引入方式
内联、嵌入、外部、导入
1. 四种引入方式
内联样式
<p style="color: red;">内联样式</p>
优先级最高、无法复用、不推荐。
嵌入样式
<style>
p {
color: blue;
}
</style>
仅当前页面有效、无法缓存。
外部样式表
<link rel="stylesheet" href="styles.css" />
可复用、可缓存、推荐方式。
@import 导入
@import url('reset.css');
串行加载(性能差)、避免在顶层使用。
2. 对比
| 方式 | 复用性 | 缓存 | 性能 | 推荐度 |
|---|---|---|---|---|
| 内联 | 差 | ⭐ | ||
| 嵌入 | 中 | ⭐⭐ | ||
| 外部 | 好 | ⭐⭐⭐⭐⭐ | ||
| @import | 差 | ⭐⭐ |
3. 关键 CSS 内联
<head>
<style>
.hero {
height: 100vh;
}
</style>
<link rel="preload" href="styles.css" as="style" onload="this.rel='stylesheet'" />
</head>