0

I've been trying to get my css to select the 'correct' first div but can't seem to isolate it. Here's my (stripped back, but correct) html:

<div id="page_container">
    <div></div> // this div has content, but no id or class
    <div class="holder"></div> // this div has content
    <div class="section"></div> // <<<< this is the div I want to select; the first div with the class 'section'
    <div class="section"></div> // I don't want to select other 'section's
    <div class="section"></div>
    <div class="section"></div>
</div>

CSS-wise, so far I have tried...

#page_container > div > .section:first-child {
    ...rules here
}

#page_container > div:first-child(.section) { // is this even valid?
    ...rules here
}

#page_container > div > div > .section:first-child {
    ...rules here
}

...without luck.

I may be experiencing a brain-fart, but how would I select just the first div with a class of 'section'?

Any help, much appreciated!

moosefetcher
  • 1,841
  • 2
  • 23
  • 39

2 Answers2

4

Try this.

#page_container .section{
  background: green;
  margin: 10px 0;
}

#page_container .section ~ .section {
    background: transparent;
}
<div id="page_container">
    <div>this div has content, but no id or class</div>
    <div class="holder">this div has content</div>
    <div class="section">this is the div I want to select; the first div with the class 'section'</div>
    <div class="section">I don't want to select other 'section's</div>
    <div class="section"></div>
    <div class="section"></div>
</div>
Pons Purushothaman
  • 2,225
  • 1
  • 14
  • 23
2

You could use + Combinator.

Adjacent sibling combinator

The + combinator selects adjacent siblings. This means that the second element directly follows the first, and both share the same parent.

Syntax: A + B

Example: h2 + p will match all <p> elements that directly follow an <h2>.

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

Example:

#page_container > .holder + .section {
    background: red;
}
<div id="page_container">
    <div>this div has content, but no id or class</div> 
    <div class="holder">this div has content</div> 
    <div class="section">this is the div I want to select; the first div with the class 'section'</div>
    <div class="section">I don't want to select other 'section's</div>  
    <div class="section"></div>
    <div class="section"></div>
</div>
Community
  • 1
  • 1
Mhd Alaa Alhaj
  • 2,438
  • 1
  • 11
  • 18
  • Thanks for your reply. I maybe should have said that the actual page html is generated dynamically (angular.js), so I can't always guarantee that the 'holder' div will be present. Therefore I really need the css to focus on the 'section' class. – moosefetcher Nov 29 '17 at 13:12
  • you are most welcome – Mhd Alaa Alhaj Nov 30 '17 at 05:15