DrillLab
第 10 / 105 道10 / 105 · #270

有几种方式引入 CSS

How many ways to import CSS in your project

先自己答,再往下看Answer it yourself first

一句话:传统上三种 —— 行内 style 属性、页内<style> 标签、外部<link> 文件(外加 CSS 里的@import)。

但面试问这题,其实想听你说现代工程里的做法:

  • 普通 import——import "./styles.css", 打包工具接管,全局生效。
  • CSS Modules——import s from "./x.module.css", 类名自动加哈希,天然不冲突
  • CSS-in-JS(styled-components、emotion)—— 样式写在 JS 里,能用 props 做条件样式。 代价是运行时开销。
  • 原子化(Tailwind)—— 不写 CSS,直接堆预设类名。

会追问:「为什么不推荐 @import?」—— 因为它是串行的: 浏览器要先下载并解析外层 CSS, 才发现里面还有个 @import,再去下载。 这形成了一条请求链,直接拖慢首屏。 构建工具里的 @import 是编译期合并的, 不算这个问题 —— 说清这个区别是加分项。

In one line: traditionally three — an inline style attribute, an in-page <style> tag, an external file via <link> (plus@import from within CSS).

But what the interviewer wants is how it is done in a modern build:

  • Plain import import "./styles.css"; the bundler takes over, styles are global.
  • CSS Modules import s from "./x.module.css"; class names are hashed, so collisions are impossible by construction.
  • CSS-in-JS (styled-components, emotion) — styles live in JS, so props can drive them. The cost is runtime work.
  • Atomic (Tailwind) — you do not write CSS, you compose preset class names.

Follow-up: “Why is @import discouraged?” — because it is serial: the browser must download and parse the outer stylesheet before it even discovers the@import, then fetch again. That request chain delays first paint. @import handled by a build tool is merged at compile time and does not have this problem — pointing out that distinction is what earns the marks.