Skip to content

[css-nesting-2] Syntax to customize how a nest-containing selector is resolved? #6330

Closed
@flachware

Description

@flachware

I’m very exited about the upcoming nesting feature (https://drafts.csswg.org/css-nesting/). But with nesting new troubles emerge. This is a proposal for a Sass-like :selector-replace() pseudo-class function that allows authors to modify the nesting selector &.

In complex user interfaces elements tend to have multiple states which depend in part on parent elements. The deeper an element is nested the more likely it becomes that you have to define a state that is based on a modified selector somewhere in the middle of the 'selector chain'.

Example:

.component {
  color: green;
  
  & .container {
    color: brown;
  }
  
  & .child {
    color: blue;
    
    &:hover {
      color: yellow;
    }
    
    &:selector-replace(.component, .component:focus) {
      color: red;
    }
    
    &:selector-replace(.component, .component .container.active) {
      color: white;
    }
  }
}

is equivalent to

.component {
  color: green;
}

.component .container {
  color: brown;
}

.component .child {
  color: blue;
}

.component .child:hover {
  color: yellow;
}

.component:focus .child {
  color: red;
}

.component .container.active .child {
  color: white;
}

In this simplified example the .child element has four states, two of these states depend on its ancestors. Of course this could be written by adding these states to .component and .container. But this would not be DRY and the .child styles start to scatter around, in the worst case you would have to replicate the nesting multiple times in various places just for one modified part at a time (and there would be a lot more nesting levels and elements in reality).

The proposed :selector-replace() pseudo-class function addresses this issue by allowing you to modify nested selectors wherever you need it. I do not propose that particular name, I think something like :mod() (modify) might make more sense with regard to brevity.

Disclaimer: I did not come up with this feature, it is part of Sass – for good reason.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions