Search code examples
htmlcsscss-selectorscss-modules

Select an element without selecting descendants


I use CSS Modules which generates random class names for my tags. How can I select an element of specific type without selecting descendants? So far I've tried to use selectors :first-of-type and :first-child like this:

.settings ul:first-of-type > i:first-child {
    opacity: 0.5;
}

But the result is that my rule applies to every <i> element on my page.

HTML:

<div class="settings">
    <ul>
        <li>
            <i>Select this element</i>
            <ul>
                <li>
                    <i>but not this one</i>
                    <span></span>
                </li>
                <li>
                    <i>or not this one</i>
                    <span></span>
                </li>
            </ul>
        </li>
    </ul>
</div>

Solution

  • Use the CSS child combinator >:

    .settings > ul > li > i {
      opacity: 0.5;
    }
    <div class="settings">
      <ul>
        <li>
          <i>Select this element</i>
          <ul>
            <li>
              <i>but not this one</i>
              <span></span>
            </li>
            <li>
              <i>or not this one</i>
              <span></span>
            </li>
          </ul>
        </li>
      </ul>
    </div>

    The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first.