Why is a second-child affected by my first-child color property?

后端 未结 4 1443
野性不改
野性不改 2021-01-16 21:47

I was finishing up selectors and testing my knowledge and encountered a problem that makes no sense.

In theory, the code below should color all first children that

相关标签:
4条回答
  • This is because you have nested lis.

    The second inner li is being coloured red because it's inheriting that rule from the style applied to the first child outer li, ie its parent.

    li:first-child { color: red; }
    li:not(:first-child) { color: black; }
    

    That will override the inheritance and result in the text of the first outer and inner lis being red. Fiddle

    Alternatively, if you want to colour only the inner lis:

    li li:first-child { color: red; }
    
    0 讨论(0)
  • 2021-01-16 22:16

    It happens because the color is inherited from the parent element, try to add this to your CSS to override it:

    li {
        color:initial;
    }
    
    0 讨论(0)
  • 2021-01-16 22:24

    color is inherited from the parent element....in this case the li:first-child

    So when you tell the li to be a red color this is inherited by all its children.

    You have no rule to override this for the children so they are colored by inheritance/

    0 讨论(0)
  • 2021-01-16 22:32

    The li:first-child selector will also select the first li element in your parent list. You can target your selector using direct descendents or you can use classes.

    Option 1: class selector on parent list

    This is the preferred option as it will automatically namespace your css. All your selectors will start with .menu when targeting child elements.

    <ul class="menu">
        <li>Peter<ol>
            <li>Juan</li>
            <li>Samuel</li>
        </ol></li>
    </ul>
    
    .menu ol li:first-child{
      color: red;
    }
    

    If you want to override the style of a menu, you can use an extra class on the menu element and for example target it with the following selector. .menu.horizontal

    Option 2: class selector on list item

    This option has the same benefits of the first option, but now .menuItem is namespaced on its own.

    <ul>
        <li class="menuItem">Peter<ol>
            <li>Juan</li>
            <li>Samuel</li>
        </ol></li>
    </ul>
    
    .menuItem ol li:first-child{
      color: red;
    }
    

    Option 3: direct descendent selector

    ol>li:first-child{
      color: red;
    }
    

    It is always better to use classes because if you use ol elements in other places, the selector would still apply there.

    0 讨论(0)
提交回复
热议问题