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

后端 未结 4 1500
野性不改
野性不改 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条回答
  •  孤城傲影
    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.

    
    
    .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.

    .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.

提交回复
热议问题