如何用SCSS优雅选择父级元素?优化导航样式代码结构
Hey there! The issue with your desired nested structure is that the .active class lives on the parent .nav-item, not as a child of .nav-materials. To target the active state while keeping the styling nested under .nav-materials, you can use SCSS's @at-root directive combined with the parent selector & to jump up the hierarchy and target the correct parent class.
Your Original HTML
<ul id="navbar-main" class="navbar-nav mr-auto"> <li class="nav-item active"> <a href="https://travian.dev/materials" class="nav-link nav-materials"> <span class="invisible">Materials</span> </a> </li> </ul>
Your Current SCSS (Working but Split)
#navbar-main { li { &.nav-item { .nav-link { width: 50px; height: 50px; background: no-repeat center; background-size: contain; &.nav-materials { background-image: url('../images/buttons/menu-materials.png'); } } &.active { .nav-link { &.nav-materials { background: red; } } } } } }
Optimized SCSS (Nested as Desired)
Here's how you can restructure the code to keep the active state styling nested inside .nav-materials:
#navbar-main { li { &.nav-item { .nav-link { width: 50px; height: 50px; background: no-repeat center; background-size: contain; &.nav-materials { background-image: url('../images/buttons/menu-materials.png'); // Target the parent .nav-item.active and apply styles to & (which is .nav-link.nav-materials) @at-root .nav-item.active & { background: red; } } } } } }
How This Works
- The
&inside.nav-materialsrefers to.nav-link.nav-materials. @at-rootbreaks out of the current nested context, so we can directly target.nav-item.activefollowed by&(our.nav-link.nav-materialsselector).- This compiles to the exact CSS selector you need:
.nav-item.active .nav-link.nav-materials.
Alternatively, if you want to avoid @at-root, you could use a parent reference chain, but @at-root makes the intent clearer and keeps the code clean.
Compiled CSS Output
The optimized SCSS will compile to this (same as your original working CSS):
#navbar-main li.nav-item .nav-link { width: 50px; height: 50px; background: no-repeat center; background-size: contain; } #navbar-main li.nav-item .nav-link.nav-materials { background-image: url("../images/buttons/menu-materials.png"); } #navbar-main li.nav-item.active .nav-link.nav-materials { background: red; }
This structure keeps all related styles for .nav-materials in one place, making your code more maintainable and readable as requested.
内容的提问来源于stack exchange,提问作者user936965

