fightstarr20
fightstarr20

Reputation: 12578

CSS first-of-type applying to all elements

I am trying to use first-of-type to style only the first .menu element in this layout...

.menu:first-of-type
{
  background:red;
}
<div id="container">
    <section>
        <div>
            <ul class="menu">
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
            </ul>
        </div>
    </section>
    <section>
        <div>
            <ul class="menu">
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
            </ul>
        </div>
    </section>
    <section>
        <div>
            <ul class="menu">
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
            </ul>
        </div>
    </section>
<section>
  <div>
  <ul class="menu">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  </ul>
  </div>
</section>

<section>
  <div>
  <ul class="menu">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  </ul>
  </div>
</section>
</div>

</div>

It is applying the background color to all, where am I going wrong?

Upvotes: 1

Views: 251

Answers (2)

IiroP
IiroP

Reputation: 1102

:first-of-type targets first child of specific type. As these elements have different parents, the all are first childs. You can prevent this by adding class to <section> and using it for that:

.menuSection:first-of-type {
  background: red;
}
<div id="container">
  <section class="menuSection">
    <div>
      <ul class="menu">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    </div>
  </section>
  <section class="menuSection">
    <div>
      <ul class="menu">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    </div>
  </section>
  <section class="menuSection">
    <div>
      <ul class="menu">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    </div>
  </section>
  <section class="menuSection">
    <div>
      <ul class="menu">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    </div>
  </section>

  <section class="menuSection">
    <div>
      <ul class="menu">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    </div>
  </section>
</div>

Upvotes: 1

Grzegorz Aperliński
Grzegorz Aperliński

Reputation: 918

This is because :first-of-type makes the rule apply to every element that is first of the type within its parent element. You need to capture the first section element and then style the menu element like so:

  section:first-of-type .menu
    {
      background:red;
    }

Upvotes: 2

Related Questions