/

How to Select the First Child Element with CSS

How to Select the First Child Element with CSS

Problem: I encountered a situation in my markdown file where I needed to style the first ul element, which happened to be the table of contents. However, I couldn’t assign a class or an id to specifically target it with CSS.

In order to address this, I explored ways to select it using a suitable CSS selector.

The HTML structure looked like this:

1
2
3
4
5
6
<div id="content">
<ul>
...table of contents
</ul>
...remainder of the HTML
</div>

To solve the problem and only apply the desired styles to the first child ul within the div#content, I used the following CSS code:

1
2
3
div#content > ul:first-of-type {
...my styles
}

Tags: CSS, first-child element, selector, styling