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

如何为交替entry元素内的imageContain设置差异化样式?

如何为交替的.entry元素内的.imageContain设置样式?

问题场景

现有如下HTML结构:

<div class="entry">
  <div class="imageContain">
    <img src="photo1">
  </div>
  <div class="title">Blah</div>
  <div class="text">Whatever</div>
</div>
<div class="entry">
  <div class="imageContain">
    <img src="photo2">
  </div>
  <div class="title">Foo</div>
  <div class="text">Some stuff</div>
</div>

需求是为每隔一个.entry元素内的.imageContain设置不同样式,但尝试的两种写法都存在问题:

  1. 以下写法仅在Chrome生效,Firefox会忽略:
.entry:nth-of-type(odd) {
  .imageContain {
    background-color: red;
  }
}
  1. 以下写法在Chrome和Firefox中均无效:
.entry:nth-of-type(odd).imageContain {
  background-color: red;
}

问题原因

  • 第一种写法是Sass/Scss的嵌套语法,并非标准CSS。Chrome能生效是因为项目可能经过预编译处理,但Firefox直接解析时无法识别这种嵌套结构,因此会忽略该规则。
  • 第二种写法的选择器逻辑错误:.entry:nth-of-type(odd).imageContain表示同时拥有.entry和.imageContain类的元素,而我们需要选中的是.entry元素内部的.imageContain子元素,两者逻辑完全不符。

正确写法

使用标准CSS的后代选择器(空格分隔),即可在所有现代浏览器中生效:

.entry:nth-of-type(odd) .imageContain {
  background-color: red;
}

如果只需要选中.entry的直接子元素(避免影响嵌套更深的同名元素),可以使用直接子选择器>:

.entry:nth-of-type(odd) > .imageContain {
  background-color: red;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:05:55