Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a CSS "#id element" select grandchildren as well?

Say I have a <div id="container"> with various elements inside of it including tables. Does the CSS selector #container table select all tables within the div (including grandchildren, great-grandchildren, etc)? Or does it select children only?

Also, if I want to select the first child div within the container div, how would I do that?

like image 282
Justin Avatar asked Oct 02 '12 14:10

Justin


2 Answers

#container table will select all the table elements that are inside of the #container element, no matter how deep in the DOM tree they are. If you want to target only the first level elements, you'd go about using this: #container > table

To select the first child div within the container element, you'd do the following: #container > div:first-child - this will select only the first level child div. Or, if you want to target all first div elements within the container, you'd use #container div:first-child

This is valid only if the div is actually the first child of that element

<div id="container">
    <div>some content</div>
</div>

so, for example there must not be any p tag before it (or any other).

<div id="container">
    <p>Some text</p>
    <div>some content</div>
</div>

If the div is not the first child, you'd need to do the following: #container div:first-of-type

like image 150
Lazar Vuckovic Avatar answered Sep 18 '22 19:09

Lazar Vuckovic


Yes; to put it simply, that selects all table elements within #container, regardless of nesting level.

The space is called the descendant combinator. As exactly what it says on the tin, it selects any descendants. That includes children, grandchildren, etc, again regardless of nesting level. It does not only select children; that purpose is served by the child combinator >.1

To select the first child within your container as a div, you use

#container > div:first-child

Or if you have something else as the first child and you want to pick the first child that is of type div, you use

#container > div:first-of-type

1For this purpose, it's often said to select only "direct children", and where people say "children" they often mean "descendants" instead. Strictly speaking, though, "children" refers to immediate nesting level. There's no such thing as an "indirect child".

like image 37
BoltClock Avatar answered Sep 20 '22 19:09

BoltClock