使用&切换父元素:after伪元素图标遇问题,求正确用法指导
Hey there! Let's clear up how to use the SCSS & parent selector correctly to swap icons on :after pseudo-elements when the parent class changes.
First, let's break down why your current approach is generating unexpected selectors:
The & in SCSS represents the complete parent selector chain from your current nesting level. When you write something like .box-example-default & inside a .box-header nested block, & gets replaced with the full path up to that point (e.g., #pageContainer .box .box-header), resulting in .box-example-default #pageContainer .box .box-header—which is not targeting the .box element with the extra class, as you intended.
Correct Approaches
Let’s cover two common scenarios you might be working with:
1. Swapping the :after icon on the .box element itself
If you want to modify the .box:after pseudo-element when .box has an additional class like .box-example-default, structure your SCSS like this:
#pageContainer { .box { // Base style for .box:after &:after { content: "\f007"; // Default icon (Font Awesome example) // Other styles: position, color, etc. } // Override when .box has the .box-example-default class &.box-example-default:after { content: "\f001"; // New icon } } }
This compiles to clean CSS:
#pageContainer .box:after { /* base styles */ } #pageContainer .box.box-example-default:after { /* overridden styles */ }
2. Swapping the :after icon on a child element (e.g., .box-header)
If the pseudo-element is on .box-header and you want to change it when the parent .box has a different class, nest the override within the .box level:
#pageContainer { .box { .box-header { // Base style for .box-header:after &:after { content: "\f007"; } } // Override .box-header:after when .box has .box-example-default &.box-example-default .box-header:after { content: "\f001"; } } }
This compiles to:
#pageContainer .box .box-header:after { /* base styles */ } #pageContainer .box.box-example-default .box-header:after { /* overridden styles */ }
Key Takeaways
- Always use
&at the start of a selector modification when targeting the current parent element (e.g.,&.extra-classinstead of.extra-class &). - The
&replaces the entire parent selector chain, so nesting it correctly ensures you target the exact element/class combination you need. - Avoid reversing the order (like
.extra-class &) unless you specifically need that extra class to be an ancestor of your current selector chain.
内容的提问来源于stack exchange,提问作者bilcker

