Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select every other element of class using css3

Tags:

css

Given an ul with a structure like this:

<ul>
    <li class="product">...</li>
    <li class="product">...</li>
    <li class="product">...</li>
    <li class="product">...</li>
    <li class="spot">...</li>
    <li class="product">...</li>
    <li class="product">...</li>
</ul>

Is there any way using CSS3 to target every other occurance of a li with the class product.

I've tried using both nth-of-child and nth-of-type in various configurations to no luck, both seem to target every other li element regardless of the class is has.

like image 823
Hans Skov Avatar asked Apr 18 '12 15:04

Hans Skov


People also ask

How do you target every other element in CSS?

The :nth-child(odd) property will target every other item of the element you have selected.

How do I select all 3 elements in CSS?

formula (an + b) In addition to the value n being able to be any number, you can also use a formula. nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one.

How do I select all 3 children in CSS?

Yes, you can use what's known as :nth-child selectors. In this case you would use: li:nth-child(3n) { // Styling for every third element here. }

How do you select a class and element in CSS?

Definition and Usage To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.


1 Answers

Basically, you can't with plain CSS3. The nth-child selectors work on element selectors, not classes. So, li:nth-child(even) works, but .product:nth-child(even) does not.

You will need jQuery to achieve this.

like image 136
chipcullen Avatar answered Nov 29 '22 03:11

chipcullen