Is There a CSS Selector For the First Direct Child Only

Is there a CSS selector for the first direct child only?

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.

css for the first direct child only

Use the first child selector:

.nav-collapse .nav:first-child {}

You can combine it with the direct child selector if you have more nested .nav elements.

.nav-collapse > .nav:first-child {}

What is the CSS selector for selecting the first immediate child of an element?

The :first-child selector allows you to target the first element immediately inside another element.

<p>
<div>First child...</div>
<div>Second...</div>
<div>Third...</div>
<div>Fourth...</div>
</p>

In CSS:

p > div:first-child {
font-size: 1.5em;
}

Edit: Important note is that you should never use div inside p. I wrote this code to show you how to select first child in your case, but it's really so bad to use div inside p. Whenever you use <div> between <p> and </p> like (for example) this:

<p> <div></div> </p> 

Browser will attempt to correct (to be valid code) it to this:

<p></p> <div></div> <p></p>

Good luck!

Does :first-child work whether the type is known or unknown?

:first-child can be used with or without knowing the element type.

You can either do parent > :first-child to match any first child, whatever node type it is, or you can do parent > p:first-child to only match the first child if it's a p tag.

You can also do parent > p:first-of-type to match the first p inside parent, even if it isn't the first child.

CSS select direct child items only

You're only selecting the parent ul with >, you'll need to add another to also pick immediate children of that ul, for example:

.nav > ul > li > a:hover{
color: red;
}

You'll also need to add li > a:hover to select the anchor elements inside them, since the child <a> elements are also within the <li> scope.

How to apply CSS to first child div element only?

You can play with :first-child CSS selector, for example if you want to target the first div child of .node-master:

.node-master > div:first-child {
color: red;
}

CSS select direct children, but not if inside another nested child

Use div.parent > p.p

> is the child combinator. It matches only those elements matched by the second selector that are the direct children of elements matched by the first.