Add nested selectors #585
Replies: 3 comments 2 replies
-
Yes, that would really be useful! |
Beta Was this translation helpful? Give feedback.
-
I'm revisiting Vanilla Extract and just ran into this. How do I solve this with the example above? (I'm also using this within a a recipe variant) |
Beta Was this translation helpful? Give feedback.
-
It's not the most intuitive, but I've addressed these cases by changing my mental model for how to apply styles when there's multiple variants. I'm not 100% sure this ideal, but it worked for me. Vanilla Extract doesn't work well when trying to apply a condition-based style, then to further override that condition-based style with another condition. That's typically what we use nesting for, to dig into a complex state of conditions. What worked for me was to flatten the states, and use CSS variables to help avoiding specificity and cascade issues. So in your example, each state would be an "or", instead of "and". // create a variable for our background color
const bgColor = createVar();
// This is our base class implements where the variables are used
const base = style({
backgroundColor: bgColor
});
export const variants = styleVariants(
{
// use styleVariants to define our stateful variants
notDisabled: {
vars: {
[bgColor]: themeVars.primary50
}
},
notDisabledAndChecked: {
vars: {
[bgColor]: themeVars.primary100
},
":hover": {
vars: {
[bgColor]: themeVars.primary200
}
},
":focus": {
vars: {
[bgColor]: themeVars.primary300
}
},
":active": {
vars: {
[bgColor]: themeVars.primary400
}
}
}
},
// Compose with the base
(variant) => [base, variant]
); Now the complexity of the conditions is handled in the implementation: getVariantClass(disabled, checked) {
if (disabled) {
return '';
}
return variants[checked ? 'notDisabledAndChecked' : 'notDisabled'];
} Pros of this solution:
Cons of this solution:
I think if you wanted to continue using data-attributes, you could roll your own |
Beta Was this translation helpful? Give feedback.
-
Nested selectors would allow for more composability, readability, and smaller selector.
Beta Was this translation helpful? Give feedback.
All reactions