You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SCSS中&::before的含义是什么?是否用于为宿主元素前的元素设置样式?

Understanding &::before in SCSS

Hey there! Let's break down exactly what this syntax does and clear up your question about it.

First, split the syntax into two key parts:

  • &: This is SCSS's parent selector reference. When writing nested styles, & gets directly replaced with the parent selector wrapping it. It’s a huge help for keeping code organized instead of repeating selectors over and over.
  • ::before: This is a native CSS pseudo-element. It creates a virtual inline-level element that inserts itself right before the content of its host element. A critical note: this pseudo-element won’t render at all unless you define a content property (even if it’s just an empty string "").

Putting it all together: &::before

Combining these two lets you target the ::before pseudo-element of your current parent selector—all within SCSS’s nested structure. This keeps your styles grouped logically under the parent element, making code cleaner and easier to maintain.

Concrete example:

Here’s how you’d write it in SCSS:

.alert {
  padding: 1rem;
  border: 1px solid #ccc;

  &::before {
    content: "⚠️";
    margin-right: 0.5rem;
    font-size: 1.2rem;
  }
}

When compiled to regular CSS, this becomes:

.alert {
  padding: 1rem;
  border: 1px solid #ccc;
}
.alert::before {
  content: "⚠️";
  margin-right: 0.5rem;
  font-size: 1.2rem;
}

To answer your specific question:

Yes, it does style a virtual element that appears before the host element’s content—but it’s not a separate sibling element sitting before the host in the DOM. This pseudo-element is attached directly to the host element and is part of its rendering structure.

内容的提问来源于stack exchange,提问作者DannyD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:04:07