Home » Html » How do I select every other div class element using just CSS (no js)

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

Thank you kindly for your responses in advance.

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. Thanks again friends. 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>
Answers:

You want nth-child() on .item.

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

Demo: jsFiddle

Questions:
Answers:
.item:nth-child(even) {...}
.item:nth-child(odd) {...}

demo: http://jsfiddle.net/DuL24/1/

Questions:
Answers:

Maybe it’s possible when we use this:

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

or

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

You can see my screenshots: http://screencast.com/t/17g9joVj8Z
I hope you get what you need.

Questions:
Answers:

you should set nth-of-type to .item element:

#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;}