[css] What CSS selector can be used to select the first div within another div

I have something like:

<div id="content>

   <h1>Welcome to Motor City Deli!</h1>
   <div style=" font-size: 1.2em; font-weight: bolder;">Sep 19, 2010</div>
   <div > ... </div>

What is the css selector for the second div (1st div within the "content" div) such that I can set the font color of the date within that div?

This question is related to css css-selectors

The answer is


You want

#content div:first-child {
/*css*/
}

If we can assume that the H1 is always going to be there, then

div h1+div {...}

but don't be afraid to specify the id of the content div:

#content h1+div {...}

That's about as good as you can get cross-browser right now without resorting to a JavaScript library like jQuery. Using h1+div ensures that only the first div after the H1 gets the style. There are alternatives, but they rely on CSS3 selectors, and thus won't work on most IE installs.


The closest thing to what you're looking for is the :first-child pseudoclass; unfortunately this will not work in your case because you have an <h1> before the <div>s. What I would suggest is that you either add a class to the <div>, like <div class="first"> and then style it that way, or use jQuery if you really can't add a class:

$('#content > div:first')


The MOST CORRECT answer to your question is...

#content > div:first-of-type { /* css */ }

This will apply the CSS to the first div that is a direct child of #content (which may or may not be the first child element of #content)

Another option:

#content > div:nth-of-type(1) { /* css */ }