CSS伪类相关代码中+选择器与&符号的作用是什么?
First, a quick heads-up: The & symbol you’re seeing isn’t part of standard CSS—it’s a feature of CSS preprocessors like Sass or Less. It acts as a stand-in for the parent selector from the outer rule. Let’s break down both the + and & using your code example.
The + Selector (Adjacent Sibling Combinator)
The + is a standard CSS combinator called the adjacent sibling selector. It targets an element that’s the immediately following sibling of the element before the +.
For context, imagine you have HTML like this:
<input class="check-tag__input" type="checkbox"> <label class="check-tag__label">Tag Label</label>
The selector .check-tag__input:focus + .check-tag__label would target the <label> element only when the adjacent <input> is in focus.
The & Symbol (Parent Selector in Preprocessors)
In preprocessors like Sass, & replaces itself with the parent selector of the current nested rule. Your code is almost certainly nested inside a parent rule for the element that comes right after the input. Let’s assume your full Sass code looks like this:
.check-tag__label { .check-tag__input:focus + & { outline: none; background-color: #bbb; } .check-tag__input:checked + & { background-color: #BADA55; color: #fff; } }
When this compiles to standard CSS, the & gets swapped out for the parent selector .check-tag__label, resulting in:
.check-tag__input:focus + .check-tag__label { outline: none; background-color: #bbb; } .check-tag__input:checked + .check-tag__label { background-color: #BADA55; color: #fff; }
Putting It All Together for Your Code
Let’s map this directly to your snippets:
.check-tag__input:focus + &: When the.check-tag__inputis focused, the immediately following sibling (the parent element, like.check-tag__label) will lose its outline and get a gray background..check-tag__input:checked + &: When the.check-tag__inputis checked (e.g., a checkbox toggled on), the adjacent sibling element will get a greenish background (#BADA55) and white text.
This pattern is super common for styling labels paired with form inputs, letting you update the label’s appearance based on the input’s state.
内容的提问来源于stack exchange,提问作者karunesh

