Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with odd/even child elements in nth-child

I have a web site like this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="article_style.css" />
</head>
<body>
    <div class="section">
    <!--<h1>header</h1>-->
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
    </div>
    <div class="section">
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
    </div>
</body>
</html>

and this is CSS:

div.section
{
    border: 1px solid black;
}
div.section div:nth-child(even)
{
    color: Green;
}
div.section div:nth-child(odd)
{
    color: Red;
}

And this is the result:

result

This is OK because I get red for odd div and green for even in each section. But when I add header at the begginig of first section (commented code in sample) I get this:

result2

I don't want that. I want the to have like before, but just with a header in first section. So at first header and then red paragraph.

like image 831
Mariusz Pawelski Avatar asked Mar 04 '11 15:03

Mariusz Pawelski


People also ask

Can nth kids be odd?

Definition and Usage. 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).

What is nth child odd?

tr:nth-child(odd) or tr:nth-child(2n+1) Represents the odd rows of an HTML table: 1, 3, 5, etc. tr:nth-child(even) or tr:nth-child(2n) Represents the even rows of an HTML table: 2, 4, 6, etc.

What is nth of type 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

Use nth-of-type instead:

Live Demo

div.section
{
    border: 1px solid black;
}
div.section div:nth-of-type(even)
{
    color: Green;
}
div.section div:nth-of-type(odd)
{
    color: Red;
}
like image 116
thirtydot Avatar answered Oct 13 '22 17:10

thirtydot