0

I'm trying to use pseudo-selectors rather than tag things with an individual ID if I can help it, as I have been led to believe that this is better coding.

I have three text containers, and I would like the middle one to have a different background colour for design purposes. Whichever pseudo-selector I use, I unable to select only the container, and not its children. Having experimented with nth-of-type and nth-child, I can either select the container as well as text within it, or select the container as well as text within another container.

How do I use a pseudo-selector to select only the middle container and not its contents?

My code:

<section id="section">
   <span class="container">
       <h3>Heading 1</h3>
       <p>Text</p>
   </span>
   <span class="container">
       <h3>Heading 2</h3>
       <p>Text</p>
   </span>
   <span class="container">
       <h3>Heading 3</h3>
       <p>Text</p>
   </span>
</section> ```

Css:
#section :nth-child(3) {
    background-color: red;
}


                
Ken Lee
  • 1
  • 1

1 Answers1

0

The problem with using #section :nth-child(2) is that every element that is the second child of any element within #section is selected. Hence you get all the texts given red background color.

There is also a problem with having divs etc within a span element. For more detail on this see for example: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span

This snippet changes the spans to divs and makes sure that only those elements that are direct children of section are selected by using the > selector.

#section> :nth-child(2) {
  background-color: red;
}
<section id="section">
  <div class="container">
    <h3>Heading 1</h3>
    <p>Text</p>
  </div>
  <div class="container">
    <h3>Heading 2</h3>
    <p>Text</p>
  </div>
  <div class="container">
    <h3>Heading 3</h3>
    <p>Text</p>
  </div>
</section>
A Haworth
  • 30,908
  • 4
  • 11
  • 14
  • Thank you for solving this for me, I can see it having plenty of use going forward, and I learnt more about when best to use div vs span. – Ken Lee Jun 13 '22 at 22:45