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

如何仅为指定id元素下的class元素设置CSS样式?

解决方法:正确选中#hello后代的.setcolor元素

你之前用的#hello>*.setcolor是直接子元素选择器,只会匹配#hello的直接子节点里带.setcolor类的元素,但你的目标元素是#hello的孙元素,所以这个选择器根本匹配不到它。

要选中#hello下所有层级的后代里的.setcolor元素,用后代选择器就行——把>去掉,写成#hello .setcolor,空格就代表“任意层级的后代”。

修改后的CSS

#hello .setcolor {
  background-color: blue;
}

原HTML(无需修改)

<div id="hello">
  <div>
    <div class="setcolor">
      blue
    </div>
  </div>
</div>
<div class="setcolor">
  not blue!
</div>

这样设置后,只有#hello内部文本为“blue”的元素会显示蓝色背景,外部的“not blue!”元素不会被影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:04:53