html - 仅使用 CSS 定位页面上类的每个实例以获得自定义背景颜色

标签 html css css-selectors

我的页面上重复了 3 次相同的代码,我需要定位 ImageSection-hold 类并为每个代码设置不同的背景颜色。

我无法通过 HTML 或 Javascript 添加或删除任何类,这必须使用 CSS 来完成。

尝试: 1.).ImageSection-hold:nth-of-type(1) -这将所有背景更改为相同的颜色 2.) .ImageSection-hold{ 背景颜色:#fff;} .ImageSection-hold~.ImageSection-hold{ 背景颜色:#000;}

<section class="section ImageSection">
  <div class="container">
    <div class="ImageSection-hold">
      <div class="ImageSection__desc">
      </div>
    </div>
  </div>
</section>
<section class="section ImageSection">
  <div class="container">
    <div class="ImageSection-hold">
      <div class="ImageSection__desc">
      </div>
    </div>
  </div>
</section>
<section class="section ImageSection">
  <div class="container">
    <div class="ImageSection-hold">
      <div class="ImageSection__desc">
      </div>
    </div>
  </div>
</section>

最佳答案

您可以使用nth-child 选择器。更多信息 here

.ImageSection:nth-child(1) .ImageSection-hold{
   background-color: red
}
.ImageSection:nth-child(2) .ImageSection-hold{
   background-color: green
}
.ImageSection:nth-child(3) .ImageSection-hold{
   background-color: blue
}
<section class="section ImageSection">
  <div class="container">
    <div class="ImageSection-hold">
      <div class="ImageSection__desc">
        asd
      </div>
    </div>
  </div>
</section>
<section class="section ImageSection">
  <div class="container">
    <div class="ImageSection-hold">
      <div class="ImageSection__desc">
      zxc
      </div>
    </div>
  </div>
</section>
<section class="section ImageSection">
  <div class="container">
    <div class="ImageSection-hold">
      <div class="ImageSection__desc">
      qwe
      </div>
    </div>
  </div>
</section>

关于html - 仅使用 CSS 定位页面上类的每个实例以获得自定义背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57925205/

相关文章:

css - 除了最后一项之外,我如何在所有元素上设置边框底部

html - 如何定位具有特定 css 属性的元素(仅 CSS 解决方案)?

javascript - 使用没有 ID 的 JavaScript 定位 li

javascript - 在移动 slider 时获取 slider 的值?

html - 如何将列表和文本与 div 标签并排对齐?

javascript - 固定导航隐藏在谷歌地图下并在滚动后单击时移动

css - Ng Template Bootstrap 不接受我的 CSS 类

javascript - JS 不支持 HTML(基本)

javascript - 选择类但仅将样式应用于一个单击的元素

css - nth-child 和 bootstrap 不工作