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?
The child combinator ( > ) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Elements matched by the second selector must be the immediate children of the elements matched by the first selector.
Using :first-child is very similar to :first-of-type but with one critical difference: it is less specific. :first-child will only try to match the immediate first child of a parent element, while first-of-type will match the first occurrence of a specified element, even if it doesn't come absolutely first in the HTML.
The CSS child combinator ( > ) can be used to select all elements that are the immediate children of a specified element. A combinator combines and explains the relationship between two or more selectors.
The first-child is a pseudo class in CSS which represents the first element among a group of sibling elements. The :first-child Selector is used to target the first child element of it's parent for styling. Example: HTML.
What you posted literally means "Find any divs that are inside of section divs and are the first child of their parent." The sub contains one tag that matches that description.
It is unclear to me whether you want both children of the main div or not. If so, use this:
div.section > div
If you only want the header, use this:
div.section > div:first-child
Using the >
changes the description to: "Find any divs that are the direct descendents of section divs" which is what you want.
Please note that all major browsers support this method, except IE6. If IE6 support is mission-critical, you will have to add classes to the child divs and use that, instead. Otherwise, it's not worth caring about.
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 { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With