0

ul {
  display: inline-block;
  list-style: none;
  text-align: center;
}

ul::after {
  display: table;
  content: "";
  clear: both;
}

ul:first-child {
  background-color: red;
  margin-left: 2rem;
}

li {
  float: left;
}
<body>
  <ul>
    <li>House</li>
    <li>Dog</li>
  </ul>
</body>

With the Code above, find it weird that the :first-child selector (pseudo class) is not working. I would have assumed that the li with House would have a red background. Instead there is no red background. Do you guys know why?

https://codepen.io/anon/pen/zQyVzM

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Xen_mar
  • 8,330
  • 11
  • 51
  • 74

1 Answers1

3

You need to add the first-child pseudo class to the li tag, not the ul.

li:first-child {
  background-color: red;
  margin-left: 2rem;
}

As per the MDN documentation it selects the first element among it's siblings of the same element.

Samuel Cooper
  • 552
  • 3
  • 11