I have the following html
<div class="section">
<div>header</div>
<div>
contents
<div>sub contents 1</div>
<div>sub contents 2</div>
</div>
</div>
And the following style:
DIV.section DIV:first-child
{
...
}
For some reason that I don't understand the style is getting applied to the "sub contents 1" <div>
as well as the "header" <div>
.
I thought that the selector on the style would only apply to the first direct child of a div with a class called "section". How can I change the selector to get what I want?
This question is related to
html
css
css-selectors
The CSS selector for the direct first-child in your case is:
.section > :first-child
The direct selector is > and the first child selector is :first-child
No need for an asterisk before the : as others suggest. You could speed up the DOM searching by modifying this solution by prepending the tag:
div.section > :first-child
Found this question searching on Google. This will return the first child of a element with class container
, regardless as to what type the child is.
.container > *:first-child
{
}
div.section > div
Use div.section > div
.
Better yet, use an <h1>
tag for the heading and div.section h1
in your CSS, so as to support older browsers (that don't know about the >
) and keep your markup semantic.
CSS is called Cascading Style Sheets because the rules are inherited. Using the following selector, will select just the direct child of the parent, but its rules will be inherited by that div
's children divs
:
div.section > div { color: red }
Now, both that div
and its children will be red
. You need to cancel out whatever you set on the parent if you don't want it to inherit:
div.section > div { color: red }
div.section > div div { color: black }
Now only that single div
that is a direct child of div.section
will be red, but its children divs
will still be black.
Source: Stackoverflow.com