Sass/SCSS中&$selected的CSS等价写法及Material-UI样式覆盖问题
&$selected in Material-UI Styles & Fixing Your Override Issue Let's break this down clearly—working with Material-UI's JSS-based styling can throw you for a loop if you're not familiar with how it extends CSS rules.
What &$selected Actually Does
First, let's demystify that selector syntax. Material-UI uses JSS (CSS-in-JS) under the hood, which borrows handy syntax from preprocessors like Sass:
- The
&refers to the current rule's selector—here, that's the.rootclass defined in the same style object. - The
$selectedis a local JSS reference that points directly to theselectedclass you see defined below it (selected: {}).
When this compiles to plain CSS, it turns into:
.root.selected { background-color: [theme's divider color]; }
In plain English: this style only applies to elements that have both the .root class and the .selected class at the same time.
Why Your selected Background Override Isn't Working
The most common culprit here is CSS specificity. Let's break down the issue:
- The original style uses a combined selector (
.root.selected), which has higher specificity than a standalone.selectedclass. - When you try to override it with just
selected: { backgroundColor: "your-color" }, your standalone.selectedrule gets ignored because the more specific combined selector takes precedence.
Material-UI adds both the root and selected classes to the element when it's in a selected state—so the element has both classes, and the combined rule wins out.
How to Fix the Override
You need to match (or beat) the original selector's specificity. Here are two solid approaches:
1. Use the Same Combined Selector (Recommended)
Mirror the original style structure in your custom overrides. This ensures your rule has the same specificity as the default, and if your styles are loaded after the component's default styles, yours will take priority:
const customStyles = { root: { '&$selected': { backgroundColor: 'your-custom-color' // This will override the default } }, selected: {} // Keep this empty (or add standalone styles if needed) };
2. Force the Override (Last Resort)
If you need a quick fix (though this is less maintainable long-term), you can use !important to override specificity entirely:
const customStyles = { selected: { backgroundColor: 'your-custom-color !important' } };
The Underlying Mechanics
To wrap this up, here's why this all works the way it does:
- Material-UI converts your style object keys (like
root,selected) into unique, scoped class names (e.g.,MuiListItem-root-456,MuiListItem-selected-457) to avoid global CSS conflicts. - JSS resolves local references like
$selectedto these unique class names during compilation. - CSS specificity rules still fully apply: more specific selectors (combined classes) always override less specific ones, unless you use
!importantto bypass the system.
内容的提问来源于stack exchange,提问作者Istvan Romhany González

