w3c / csswg-drafts

CSS Working Group Editor Drafts
https://drafts.csswg.org/
Other
4.5k stars 661 forks source link

CSS mixins idea using pseudo class #5789

Open mildred opened 3 years ago

mildred commented 3 years ago

I have been searching through issues to get an idea in how css mixins could be implemented in a future CSS specification. The goal is to avoid having to add class names to elements from CSS frameworks, but instead use semantic selectors and assign a style for each element.

In short, replace a danger class that puts the element in red with a CSS mixin (whatever the syntax) that can pull the red color property from elsewhere. I have been looking in particular at the @apply rule and I still have open questions about it in https://github.com/w3c/csswg-drafts/issues/532#issuecomment-744442925 and ideas in https://github.com/w3c/csswg-drafts/issues/5624#issuecomment-744469507

If the idea is to keep the way CSS is structured right now, conditionals at the top level with @supports and @media, selectors below and then properties, mixin matching could be done at the selector level using a pseudo-class. For example:

#my-error-message {
  mixin: danger message;
}

:mixin(danger) {
  background-color: red;
}

div:mixin(message) {
  border: thin black solid;
}

span:mixin(message) {
  text-decoration: underline;
}

This is pretty self-explaining, the mixin CSS property defines a list of words that can be then matched by the :mixin() pseudo-class.

I first imagined that any property could be matched and using custom properties to achieve similar result:

#my-error-message {
  --mixin-danger: on;
  --mixin-message: on;
}

:defines(--mixin-danger: on) {
  background-color: red;
}

:defines(--mixin-message: on) {
  border: thin black solid;
}

A problem with that is that the custom property is inherited by default and it would be logical for :defines(--mixin-danger: on) to match #my-error-message and its descendants. For mixins to be usable we need to avoid matching descendants.

LeaVerou commented 3 years ago

Unfortunately, using pseudo-classes is not an option, they are resolved at a totally different stage and changing that would be very problematic architecturally. @tabatkins or @emilio can elaborate.

plehegar commented 9 months ago

(as a reminder, *-needs-resolution use is reserved for horizontal groups): [[ The Accessibility Group (APA) has raised, or is following this issue, and expects it to be resolved to their satisfaction before a transition. This label is added/applied only by the APA Group, and should only be removed by them. It may replace an a11y-tracker label. ]] https://w3c.github.io/issue-metadata.html