Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get every second element if each is embedded in another one?

Tags:

css

<div class="question_container">
    <div class="views">
        <div>10</div>
    </div>
    <div>Something else</div>
</div>
<div class="question_container">
    <div class="views">
        <div>10</div>
    </div>
    <div>Something else</div>
</div>
<div class="question_container">
    <div class="views">
        <div>10</div>
    </div>
    <div>Something else</div>
</div>

How can I style every second class views in pure css.

In jquery I would do

$('*[class=views]:even').addClass('views');

But how can I do this CSS?

like image 204
yehuda Avatar asked Jun 07 '12 10:06

yehuda


People also ask

How do I select a second sibling in CSS?

You use the general sibling selector (~) in combination with :hover . The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

How do you find the nth element using CSS selector?

The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

What is nth CSS?

The :nth-of-type selector allows you select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.


1 Answers

You can use the :nth-child property for this:

Example:

.question_container:nth-child(2n) .views{
    color: red;
}

:nth-child(2) would select only the second item, while :nth-child(2n) will select every second item.

like image 107
sandeep Avatar answered Oct 13 '22 21:10

sandeep