Skip to content

Commit 5835691

Browse files
authored
Handle CSS nesting natively (#20124)
This PR introduces a new feature where we will be handling the CSS nesting ourselves. We currently still rely on Lightning CSS in most places. But there are situations where we don't use Lightning CSS out of the box: 1. During development, typically optimization/minification isn't setup 2. In places where it isn't as easy to run Lightning CSS such as in `@tailwindcss/browser` or in Tailwind Play. We handle CSS nesting in a single pass over the AST by tracking some information as we go. It's not the most complex code, but there are some tricky parts to make this happen in an efficient way, especially for the few additional optimizations we handle. While going over the AST, we will only emit CSS the moment we see declarations or comments. This also means that this has a fun side effect of removing CSS that ends up with empty nodes automatically. (Caveat: there are exceptions for body-less rules such as `@layer foo;` or `@charset "UTF-8";) This also allowed us to do some cleanup in `optimizeAst` that tried to do this as well, but now this will be handled by the code that handles nesting automatically. Which is preferred because the version in `optimizeAst` mutated the AST. This also contains some optimizations where we merge adjacent at-rules (with the same name / params), and adjacent rules with the same selector, and get rid of declarations that are duplicated in a node. (Caveat: there are exceptions, in case of `@font-family { … }` where we don't want to merge them) ~~To ensure that this implementation is correct, I also added an oracle implementation in the tests. This implementation does multiple passes over the AST, because it does each step one by one, with minimal code. Each step contains comments with examples to see what's happening in that step. We then test the optimized version against this.~~ Once the implementation was in place, and all the tests were passing, then I deleted the oracle implementation. That way we don't have to keep it in sync all the time. While handling the nesting, we have to make sure that `&` exists and if we replace it with a parent selector that we do use `:is(…)` semantics. This means that: ```css .foo { &:hover { color: red; } } ``` Becomes: ```css :is(.foo):hover { color: red; } ``` We then also make sure that we optimize the selector by removing the unnecessary `:is(…)` wrappers, but only if they were introduced by the nesting logic. If _you_ wrote `:is(…)` in your CSS, we won't touch it. If you look at the commits, the first thing we did is remove the optimization step from Lightning CSS in the tests. Then we enabled our CSS nesting handling code. This allows us to see the effect of the changes we are making. At the end, we re-enabled Lightning CSS. For now, this PR will be a step that happens before Lightning CSS is executed, while still using Lightning CSS. But now this step will also always happen in places where we don't use Lightning CSS at all. This should not result in any breaking changes. It could result in changed CSS output in environments where Lightning CSS isn't used. In environments where it is being used, then there could be some differences related to some selectors but they should result in the same behavior with the same specificity. While testing things, I noticed that there are some missed opportunities for performance related to how we extract variables from declaration values. I want to tackle `optimizeAst` in future PRs to make it simpler, more performant, and maybe even merge it with the CSS nesting handling. As part of testing this, I tested it against the tailwindcss.com codebase which contains a lot of CSS (807.67 KB, 18 174 AST nodes) because almost every utility is being used in examples. The oracle implementation is rather slow: ``` [131.59ms] ↳ oracle (step by step) [129.23ms] ↳ handleNesting(…) [ 2.32ms] ↳ toCss(…) ``` But the final code is much faster (`<15ms`): ``` [ 10.11ms] ↳ hand written (single pass) [ 8.40ms] ↳ handleNesting(…) [ 1.67ms] ↳ toCss(…) ``` In contrast, Lightning CSS takes: `[ 37.48ms] Optimized by Lightning CSS` One interesting thing to notice is that in big projects, this could add `10ms` to the build, but Lightning CSS would then take less time to process, which results in a no-op with better output. One thing to keep in mind here is that Lightning CSS does more things, such as normalizing values, handling vendor prefixes, CSS nesting, etc. <details> <summary>Some notes on how the algorithm works:</summary> ### The basic idea When you have CSS that looks this: ```css .foo { .bar { color: red; } } ``` Then the AST looks like this: ``` [ { kind: 'rule', selector: '.foo', nodes: [ { kind: 'rule', selector: '.bar', nodes: [ { kind: 'declaration', property: 'color', value: 'red', important: false } ] } ] } ] ``` When we walk this tree, and we encounter a `rule`, then we will track the selector on a stack. When we are done walking over the rule, then we will pop the selector from the stack. This means that the top-most selector on the stack will always be the parent selector. ```ts let selectorStack = [] walk(ast, { enter(node) { selectorStack.push(node.selector) }, exit(node) { selectorStack.pop() }, }) ``` The moment we encounter a `rule`, and if a previous rule was seen, then we push the `selector` of the rule onto the stack, but in a way that the `&` is already replaced by the selector. This way, a sibling rule will also get the already-prepared parent selector. The simple version looks like this: ```ts walk(ast, { enter(node) { // In the real code we properly handle `&` replacement, and make sure that // parent selector is prepended if there is no `&` used in the selector of the // node. let selector = selectorStack.length > 0 // At this point, we don't optimize anything related to the selector yet ? node.selector.replaceAll('&', `:is(${selectorStack.at(-1)})`) : node.selector selectorStack.push(selector) }, exit(node) { selectorStack.pop() }, }) ``` So far we aren't doing much yet, but the interesting part is when we encounter a `declaration` (or a `comment`). The moment we see any of those, then will we emit a node with the information from the `selectorStack`. We then also track the last node's `nodes` we created such that we can push more declarations into it as a shortcut. ```ts let result: AstNode[] = [] let nodes: AstNode[] | null = null walk(ast, { enter(node) { if (node.kind === 'declaration') { // `nodes` is available, nothing special to do if (nodes) { nodes.push(node) return } // Track new nodes let nodes = [node] // Create a new node with a reference to `nodes` for future declarations let newNode = rule(selectorStack.at(-1), nodes) result.push(newNode) } }, }) ``` The last important part is that whenever we see a new `rule`, then we have to reset that `nodes` tracking variable such that we can create a fresh node the next time we see a declaration. For the `at-rules`, something similar happens but they are tracked in a similar but separate stack. The idea there is that we can then wrap those `at-rules` around the `newNode` we create. That way the at-rules naturally float to the top. I can keep going here, but I think if you're interested in this, then you could go over the commits in this PR, or you can look at the `ast.ts` implementation directly to see what's going on. </details> ## Test plan 1. Existing tests should pass 2. New tests have been added to test the flattening of nested CSS
1 parent 9b0e8af commit 5835691

19 files changed

Lines changed: 2006 additions & 540 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1616
- Ensure fractional opacity modifiers work with named shadow sizes like `shadow-sm/12.5`, `text-shadow-sm/12.5`, `drop-shadow-sm/12.5`, and `inset-shadow-sm/12.5` ([#20302](https://github.com/tailwindlabs/tailwindcss/pull/20302))
1717
- Fix parsing selectors like `[data-foo]div` as one selector instead of two ([#20303](https://github.com/tailwindlabs/tailwindcss/pull/20303))
1818
- Fix stale `@tailwindcss/postcss` output when changed input CSS is passed from a preprocessor like Sass without updating the input file on disk ([#20310](https://github.com/tailwindlabs/tailwindcss/pull/20310))
19+
- Ensure CSS nesting is handled even when Lightning CSS isn't run, like in `@tailwindcss/browser` and Tailwind Play ([#20124](https://github.com/tailwindlabs/tailwindcss/pull/20124))
1920

2021
## [4.3.2] - 2026-06-26
2122

‎integrations/cli/plugins.test.ts‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,11 @@ test(
109109
expect(await fs.dumpFiles('dist/out.css')).toMatchInlineSnapshot(`
110110
"
111111
--- dist/out.css ---
112-
.prose-custom {
113-
:where(hr):not(:where([class~="not-prose"], [class~="not-prose"] *)) {
114-
--x: 1;
115-
@media (width >= 640px) {
116-
&.custom {
117-
--x: 2;
118-
}
112+
.prose-custom :where(hr):not(:where([class~="not-prose"], [class~="not-prose"] *)) {
113+
--x: 1;
114+
@media (width >= 640px) {
115+
&.custom {
116+
--x: 2;
119117
}
120118
}
121119
}

‎integrations/vite/index.test.ts‎

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1145,7 +1145,7 @@ test(
11451145
<link rel="stylesheet" href="./src/index.css" />
11461146
</head>
11471147
<body>
1148-
<div class="hover:flex">Hello, world!</div>
1148+
<div class="focus:text-[black]">Hello, world!</div>
11491149
</body>
11501150
`,
11511151
'src/index.css': css`
@@ -1157,16 +1157,16 @@ test(
11571157
async ({ exec, expect, fs }) => {
11581158
await exec('pnpm vite build')
11591159

1160-
let files = await fs.glob('dist/**/*.css')
1161-
expect(files).toHaveLength(1)
1162-
let [filename] = files[0]
1163-
11641160
// Should not be minified when optimize is disabled
1165-
let content = await fs.read(filename)
1166-
expect(content).toContain('.hover\\:flex {')
1167-
expect(content).toContain('&:hover {')
1168-
expect(content).toContain('@media (hover: hover) {')
1169-
expect(content).toContain('display: flex;')
1161+
expect((await fs.dumpFiles('dist/**/*.css')).replace(/-([-_a-zA-Z0-9]*?)\.css/g, '-<hash>.css'))
1162+
.toMatchInlineSnapshot(`
1163+
"
1164+
--- dist/assets/index-<hash>.css ---
1165+
.focus\\:text-\\[black\\]:focus {
1166+
color: black;
1167+
}
1168+
"
1169+
`)
11701170
},
11711171
)
11721172

@@ -1200,7 +1200,7 @@ test(
12001200
<link rel="stylesheet" href="./src/index.css" />
12011201
</head>
12021202
<body>
1203-
<div class="hover:flex">Hello, world!</div>
1203+
<div class="hover:text-[black]">Hello, world!</div>
12041204
</body>
12051205
`,
12061206
'src/index.css': css`
@@ -1212,15 +1212,17 @@ test(
12121212
async ({ exec, expect, fs }) => {
12131213
await exec('pnpm vite build')
12141214

1215-
let files = await fs.glob('dist/**/*.css')
1216-
expect(files).toHaveLength(1)
1217-
let [filename] = files[0]
1218-
1219-
// Should be optimized but not minified
1220-
let content = await fs.read(filename)
1221-
expect(content).toContain('@media (hover: hover) {')
1222-
expect(content).toContain('.hover\\:flex:hover {')
1223-
expect(content).toContain('display: flex;')
1215+
expect((await fs.dumpFiles('dist/**/*.css')).replace(/-([-_a-zA-Z0-9]*?)\.css/g, '-<hash>.css'))
1216+
.toMatchInlineSnapshot(`
1217+
"
1218+
--- dist/assets/index-<hash>.css ---
1219+
@media (hover: hover) {
1220+
.hover\\:text-\\[black\\]:hover {
1221+
color: #000;
1222+
}
1223+
}
1224+
"
1225+
`)
12241226
},
12251227
)
12261228

‎integrations/vite/resolvers.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -572,7 +572,7 @@ test(
572572
await exec('pnpm vite build')
573573

574574
expect(
575-
(await fs.dumpFiles('./dist/**/*.css')).replace(/-([_a-zA-Z0-9]*?)\.css/g, '-<hash>.css'),
575+
(await fs.dumpFiles('./dist/**/*.css')).replace(/-([-_a-zA-Z0-9]*?)\.css/g, '-<hash>.css'),
576576
).toMatchInlineSnapshot(`
577577
"
578578
--- ./dist/assets/index-<hash>.css ---
@@ -643,7 +643,7 @@ test(
643643
await exec('pnpm vite build')
644644

645645
expect(
646-
(await fs.dumpFiles('./dist/**/*.css')).replace(/-([_a-zA-Z0-9]*?)\.css/g, '-<hash>.css'),
646+
(await fs.dumpFiles('./dist/**/*.css')).replace(/-([-_a-zA-Z0-9]*?)\.css/g, '-<hash>.css'),
647647
).toMatchInlineSnapshot(`
648648
"
649649
--- ./dist/assets/index-<hash>.css ---

0 commit comments

Comments
 (0)