How to Select all Elements Except the First With the CSS :not(:first-child) Selector

Learn how to select all HTML elements except the first with the CSS `:not(:first-child) selector.

If you add the following rule-set to your CSS stylesheet, every h2 element on your entire website will get a 64px top margin.

h2 {
    margin-top: 64px;

But what if you don’t want to give that top margin to the very first h2 element in on your website in general, but every other h2 element?

Use the :not(:first-child) selector

Add the following rule-set to your stylesheet:

h2:not(:first-child) {
    margin-top: 64px;

Now every h2 element on your website will consistently get the same margin-top value — except the very first h2 element on each document (page/post).

A use case for the :not(:first-child) selector

Let’s say you’re styling your website’s typographic layout. You decide that all your articles’ h2 heading elements should have a margin-top: 64px; to give some breathing room between sections.

But at the top of every article, you have an intro section with a magazine/poster style with a cover image, an overlay and various text elements on top. In that case, you may use several heading elements (h1 for the title, h2 for the tagline, etc.).

In that case, you probably don’t want to use exactly the same spacing values (margin/padding) in your intro section, as inside your article. By using the :not(:first-child) selector, you remove that problem.

You can use this selector on every HTML element. Another common use case is if you use an unordered list <ul> for your menu. You may have some very specific styling that you want to add to the ul in your menu, but not on the rest of your site (alignment, borders, colors, etc.).

Isn’t CSS all about styling with classes now?

In modern web development, it’s popular to avoid styling element selectors directly. Most use classes now. I’m a fan of classes as well, because they make it easier to write scalable and reusable CSS on growing web platforms.

However, direct selector styling still has it’s place. It’s practical to establish some baseline/global styling directly on the element selectors to automatically instill consistency and uniformity in through your product UI. This approach can save you a lot of repetitive UI styling — when done right.

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊


Share & Discuss on