Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you select the html element or root node with nth-child?

Tags:

html

css

I was teaching one of my students about the nth-child() pseudo-selector and I asked him: Can you select any possible HTML element with the nth-child pseudo-selector? His answer was no, because you cannot select the root node or rather the html element.

I had overlooked this myself because my answer, in the past, had been yes. Is it possible to use nth-child() to select the html element? If so, how?

I'd like to know, so when I make definitive claims while teaching my students, they truly are definitive and haven't overlooked any possible corner case.

Thank you

like image 993
Kevin Behan Avatar asked Oct 09 '15 22:10

Kevin Behan


2 Answers

http://www.w3.org/TR/css3-selectors/#nth-child-pseudo:

“The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.”

like image 153
CBroe Avatar answered Sep 23 '22 21:09

CBroe


nth-child(n) should select every element. It does, except for the html element, which makes sense because html is a root element and has no parent. Having a parent element is a requirement as CBroe pointed out.

body {
    border: 5px solid black;
    margin: 10px;
}
html {
    border: 5px dashed red;
}
:nth-child(n) {
    border: 5px dotted blue;
}
<body>
    <ul>
        <li>first</li>
        <li>second</li>
        <li>kevin</li>
    </ul>
</body>
like image 22
at. Avatar answered Sep 22 '22 21:09

at.