Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

html - How do I select every other div class element using just CSS (no js)

I know how to do this using javascript and php, but I am trying to learn how/if it is possible to do this using just css.

I have a container which holds many items. Each item has a picture, and below it, a div containing a description. I want the background of the description to be different for every other item.

Is it possible to achieve this using just css? If so, how? I have been fooling around with using the selectors

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

I can't seem to get it. Suggestions, comments, anything is appreciated.
Below is some simplified sample code that demonstrates what I have going on.

<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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want nth-child() on .item.

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

Demo: jsFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...