[csswg-drafts] [css-nesting] :selector-replace() pseudo-class function (#6330)

flachware has just created a new issue for https://github.com/w3c/csswg-drafts:

== [css-nesting] :selector-replace() pseudo-class function ==
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 any preceding selector (in this case 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 list of selectors. 

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 (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.



Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/6330 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Monday, 31 May 2021 14:41:04 UTC