如何在共享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
相关产品推荐
相关产品推荐

