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

如何在共享CSS代码的类中,仅为特定类的内部p标签设置样式?

SCSS中仅为指定子容器内的元素设置样式的简洁实现

现有HTML结构

<div class="topSection">
    <div class="middleSection">
        <p>This is some text in a paragraph.</p>
    </div>
    <div class="lowerSection">
        <p>This is some text in a paragraph.</p>
    </div>
</div>

原SCSS代码(问题版本)

这段代码让.middleSection和.lowerSection共享内边距与字体大小,同时两者内部的p标签都被设置浅灰色背景:

.topSection{
    .middleSection, .lowerSection{
        padding: 20px;
        font-size: 20px;
        p{
            background-color: lightgrey;
        }
    }
}

错误的:not()尝试说明

你之前的写法无效的原因是:p:not(.lowerSection)是筛选自身没有.lowerSection类的p标签,但.lowerSection是p的父容器类,不是p自身的类,所以这个选择器完全不匹配目标元素。

.topSection{
    .middleSection, .lowerSection{
        padding: 20px;
        font-size: 20px;
        p:not(.lowerSection){
            background-color: lightgrey;
        }
    }
}

简洁解决方案(无需拆分代码)

利用SCSS的&父选择器引用,在共享样式块内精准定位.middleSection下的p标签,既保留共享样式,又无需拆分代码:

.topSection{
    .middleSection, .lowerSection{
        padding: 20px;
        font-size: 20px;
        // 仅匹配当前分组中的.middleSection容器下的p标签
        &.middleSection p {
            background-color: lightgrey;
        }
    }
}

这里的&代表当前的父选择器分组(即.middleSection, .lowerSection),&.middleSection会精准匹配分组里的.middleSection元素,再选中其内部的p标签,完美实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:37:10