CSS Trick: How to target all elements besides the first

Posted on: Wed, 01/09/2019 - 04:39 By: admin

This CSS trick is quite simple. Let's say you have:

<ul>
  <li> list item </li>
  <li> list item </li>
  <li> list item </li>
</ul>

If you want to target the first <li>, you can do it as follows:

ul li { background-color: #FFFFFF; /* applies to every li */ }

ul li:first-child { background-color: blue; /* targets only the first li */ }

This works in all major browsers.

For :first-child to work in IE8 and earlier, a <!DOCTYPE> must be declared.

Tags

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
English