w3c / w3c/csswg-drafts

[css-nesting] (Lexical?) scoping for identifiers defined in nested blocks

Open
#6,809 13 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

css-cascade-6 css-nesting-2 css-scoping-1
Dominant language
Bikeshed
Stars
4.9k
Forks
816
PR merge metrics
PR metrics pending

Description

We have currently resolved that the names defined by rules like @keyframes or @property are tree-scoped, and that does resolve the pressing issue of using them in Shadow DOM. However, it is false to assume that any and all encapsulation will ever happen via Shadow DOM. Even in light DOM, authors often use multiple stylesheets, or even write long stylesheets that benefit from actual scoping, in the same way that even JS code written by a single person benefits by not having every variable be global.

Currently Nesting is mainly syntactic sugar, but it can solve these issues quite nicely. Consider the following:

.foo {
	@keyframes fancy-fade { to { filter: opacity(0) } }

	& .baz {
		animation: 1s fancy-fade;
	}
}

.bar {
	@keyframes fancy-fade { to { opacity: 0 } }

	& .yolo {
		animation: 1s fancy-fade;
	}
}

Currently, the syntax above would be transformed to:

.foo {}
@keyframes fancy-fade { to { filter: opacity(0) } }
.foo .baz { animation: 1s fancy-fade; }

.bar {}
@keyframes fancy-fade { to { opacity: 0 } }
.bar .yolo { animation: 1s fancy-fade; }

I'd argue there is literally no case where you want fancy-fade defined inside a block to be available outside said block, and that there's no case where you'd want the animation specified in .foo .baz to use the fancy-fade keyframes defined inside .bar (which is what would currently happen).

What if we apply lexical scoping for name-defining rules specified inside another CSS rule, and enforce it at parse time? It provides a very natural way to scope things, is fully backwards-compatible (since nesting has not been implemented yet), and since it's parse-time, it might be reasonable to implement.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no repository files, tests, or entry points; start by reading the linked CSS Scoping draft and the nesting examples in the issue. Done would require an agreed specification for lexical scoping and parse-time enforcement, rather than a code patch.

Written by the indexing model from the issue text.

Assessment

Tech stack
css
Domain
frontend, web-dev
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.