How to select the first child element with CSS
By Flavio Copes
Learn the difference between :first-child and :first-of-type in CSS, and select the first list inside a container without adding a class.
~~~
Problem: in my markdown file I had the need to style the first ul, the table of contents, and I couldn’t add a class or an id to target it with CSS.
So I looked into how to target it with a selector.
The HTML structure was this:
<div id="content">
<ul>
...the TOC
</ul>
...rest of the HTML
</div>
If the ul is definitely the first child element, use :first-child:
#content > ul:first-child {
/* styles */
}
If another element might appear before the list, but you still want the first ul, use :first-of-type:
#content > ul:first-of-type {
/* styles */
}
The difference matters. :first-child means the element must be the first sibling of any type. :first-of-type means it must be the first sibling with that tag name.
~~~
Related posts about css: