【问题标题】:nth instance of class among siblings different background color using CSS [duplicate]使用CSS的兄弟姐妹中不同背景颜色的第n个类实例[重复]
【发布时间】:2021-12-31 05:54:40
【问题描述】:

我正在尝试使用不同的类名设置divs 列表的样式。我希望 divs 与 item 类交替显示为灰色和红色。

这是我期望看到的:

上面写着nothing 的那一行只是一个例子。该列表可以散布任意数量的nothing 元素。我只想用这些背景颜色设置class="item"s div 的样式。

以下是我认为使用 nth-of-type 会起作用的方法,但没有:

<html>
<head>
<style> 
.item:nth-of-type(even) {
  background: red;
}

.item:nth-of-type(odd) {
  background: gray;
}
</style>
</head>
<body>

<div class="items">
  <div class="item">first</div>
  <div class="not-item">nothing</div>
  <div class="item">second</div>
  <div class="item">third</div>
</div>

</body>
</html>

我也试过nth-child,也没有用。

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    使用nth-of-type 进行这项工作的唯一方法是让.not-item 使用不同的html 标记:

    <html>
    <head>
    <style> 
    .item:nth-of-type(even) {
      background: red;
    }
    
    .item:nth-of-type(odd) {
      background: gray;
    }
    </style>
    </head>
    <body>
    
    <div class="items">
      <div class="item">first</div>
      <span class="not-item">nothing</span>
      <div class="item">second</div>
      <div class="item">third</div>
    </div>
    
    </body>
    </html>

    【讨论】:

      【解决方案2】:

      你可以使用javascript

      <html>
      
      <head>
        <style>
          .item {
            background-color: #b4b4b4;
          }
        </style>
      </head>
      
      <body>
      
        <div class="items">
          <div class="item">first</div>
          <div class="not-item">nothing</div>
          <div class="item">second</div>
          <div class="item">third</div>
        </div>
      
      </body>
      
      <script>
        styleDivs = () => {
          let items = document.getElementsByClassName("item")
          for (let i = 0; i < items.length; i++) {
            if (i % 2) {
              items[i].style.backgroundColor = "#ff0000"
            }
          }
        }
      
        styleDivs()
      </script>
      
      </html>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 2011-01-09
        • 1970-01-01
        • 1970-01-01
        • 2020-02-15
        • 1970-01-01
        • 2012-07-23
        相关资源
        最近更新 更多