1

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>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 1
    Very useful material on 'first-of' selectors in this answer https://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class. may or may-not be of interest to OP but useful background on the subject. – Vanquished Wombat Aug 14 '20 at 13:40

1 Answers1

2

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.

j08691
  • 204,283
  • 31
  • 260
  • 272