skip to Main Content

For example I have this code:

<div class="main-element">
    <h4>Title 1</h4>
    <ul>
        <li></li>
        <li></li>
        <li>
            <h4>Title2</h4>
        </li>
    </ul>
</div>

I want to select and use the same styling on all h4 elements but I also want to put additional styles on the first one. for example I want all h4 element’s margin-top and margin-bottom to have the value of 8px, but for the first h4 element I want their margin-top to have the vaule of 0.

I’ve tried to use the :first-child and first-of-type selectors. for example:

.main-element h4 {
  color: blue;
}

.main-element h4:first-of-type {
  color: red;
}

It colors all elements red instead of only the first one.

2

Answers


  1. first-of-type will be true for both h4‘s since the second one is inside a <li>, which makes is the first child again.

    Consider adding classes to the one you wish to style

    .main-element .reset {
      margin-top: 0px;
      color: red;
    }
    
    .main-element h4 {
      margin-top: 8px;
      margin-bottom: 8px;
      color: blue;
    }
    <div class="main-element">
        <h4 class='reset'>Title 1</h4>
        <ul>
            <li></li>
            <li></li>
            <li>
                <h4>Title2</h4>
            </li>
        </ul>
    </div>
    Login or Signup to reply.
  2. first-of-type always relates to the current parent, i.e it means "first occurrence of this type within this container". So your .main-element h4:first-of-type matches every h4 that is a descendant of main-element and is the first h4 in its parent.

    If you want to style only the one that’s a direct child of the parent, you can use the ">" selector, like:

    .main-element > h4:first-of-type {
      color: red;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search