【问题标题】:How do I select every other div class element using just CSS (no js)如何仅使用 CSS(无 js)选择所有其他 div 类元素
【发布时间】:2013-02-20 18:02:55
【问题描述】:

我知道如何使用 javascript 和 php 来做到这一点,但我正在尝试了解如何/是否可以仅使用 css 来做到这一点。

我有一个装有许多物品的容器。每个项目都有一张图片,在图片下方是一个包含描述的 div。我希望每个其他项目的描述背景都不同。

是否可以仅使用 css 来实现?如果是这样,怎么做?我一直在玩弄选择器

.item:nth-child(odd){background-color:red}
.item .description:nth-of-type(odd){background-color:orange;}

我好像听不懂。建议,cmets,任何东西都值得赞赏。
下面是一些简化的示例代码,演示了我正在做的事情。

<style>
#container{width:100% height:100%;}
.item {float:left; width:250px; height:700px;}
.item img {width:250px; height:250px; float:left;}
.description {width:250px; height:450px; float:left; background-color:blue;}
.description:nth-of-type(even){background-color:red;}      // <- Here's the line!!
</style>

<html>
 <body>
  <div id="container">
   <div class="item">       //item 1
    <img src="image.jpg"/>
    <div class="description"> //This (and every odd number) I want to be blue 
     <h1>Title</h1>
     <h2>Sub Title</h2>
     <p>Lorem Ipsum dolor sit for Adun!</p>
     <a href="#">::LEARN MORE::</a>
    </div>
   </div>
   <div class="item">      //item 2 and so on...
    <img src="image.jpg"/>
    <div class="description"> //and this (and every even number, red)
     <h1>Title</h1>
     <h2>Sub Title</h2>
     <p>Lorem Ipsum dolor sit for Adun!</p>
     <a href="#">::LEARN MORE::</a>
    </div>
   </div>
  </div>
 <body>
</html>

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    你想要nth-child().item

    .item:nth-child(odd) .description {
        background-color: red;
    }
    

    演示:

    【讨论】:

    • 非常感谢! :) 真棒猫,哈哈
    • 这不起作用。您不能按类选择 nth-child,只能按元素类型。如果您将另一个 div 添加到另一个类,则赔率和偶数都会发生变化。
    • 我同意@WalturBuerk。我已经尝试过这个并且对不一致的结果感到困惑,只是意识到有时我有一个兄弟姐妹有一个不同的类,该类被计算在这个伪选择器中。无赖。
    【解决方案2】:
    .item:nth-child(even) {...}
    .item:nth-child(odd) {...}
    

    演示:http://jsfiddle.net/DuL24/1/

    【讨论】:

      【解决方案3】:

      也许当我们使用这个时有可能:

      .item:nth-of-type(odd)  .description{background-color:orange;}  
      

      .item:nth-child(odd) .description{background-color:orange;}
      

      你可以看我的截图:http://screencast.com/t/17g9joVj8Z
      我希望你能得到你需要的东西。

      【讨论】:

        【解决方案4】:

        您应该将 nth-of-type 设置为 .item 元素:

        #container{width:100% height:100%;}
        .item {float:left; width:250px; height:700px;}
        .item img {width:250px; height:250px; float:left;}
        .description {width:250px; height:450px; float:left; background-color:blue;}
        .item:nth-of-type(even) .description {background-color:red;} 
        

        【讨论】:

          猜你喜欢
          • 2012-04-30
          • 2011-10-27
          • 1970-01-01
          • 1970-01-01
          • 2021-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多