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

CssCss Selectors

Css Problem Overview


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?

Css Solutions


Solution 1 - Css

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 */ }

Solution 2 - Css

You want

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

Solution 3 - 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.

Solution 4 - Css

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')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGregHView Question on Stackoverflow
Solution 1 - CssJeremy MoritzView Answer on Stackoverflow
Solution 2 - CssCapt OtisView Answer on Stackoverflow
Solution 3 - CssStan RogersView Answer on Stackoverflow
Solution 4 - CssJosh LeitzelView Answer on Stackoverflow