How to use CSS First Item Selector?

Learn how to use CSS First Item Selectors to style your elements with precision using :first-child and :first-of-type, with clear examples and tips to enhance your web design skills.

Get Started free
How to use CSS First Item Selector
Home Guide How to use CSS First Item Selector?

How to use CSS First Item Selector?

While styling HTML elements with CSS, have you ever wanted to target specific elements without adding extra classes or IDs? That’s exactly where CSS pseudo-selectors come in. They allow you to apply styles to elements based on their position or state in the DOM, helping you keep your markup clean and uncluttered.

Overview

First Item Selectors are a subset of pseudo selectors that target the first element among the sibling elements, either the very first child of the parent or the first element of a specific kind.

Practical Use Cases of CSS First Item Selector: 

  • Navigation Menus: Highlight the first menu item for emphasis or default selection.
  • Article Layouts: Style the first paragraph or heading differently for better readability.
  • Product Listings: Feature the first product with a unique badge or layout.
  • Tables and Grids: Apply distinct styling to the first row or cell for headers.
  • List Groups: Customize the first list item to draw attention or indicate priority.

This article explores how to use selectors in CSS and their alternative selectors to target elements beyond the first one.

What is the First Item Selector in CSS?

In CSS, the First Item Selector refers to the :first-child pseudo-class, which targets the first child element within a parent container. Using this selector eliminates the need to add extra classes or IDs to the child elements, allowing styles to be applied cleanly and efficiently. It’s often used to distinguish the first element from its siblings.

The syntax for using the First Item Selector in CSS:-

element:first-child {

    /* Styles */

  }

Common use cases for the CSS property include styling the first item of the list differently or highlighting it, removing the top margin of the paragraph, and more.

To ensure your styles render consistently across various browsers and devices, consider testing them with BrowserStack Live. It allows you to test your website in real time across a wide range of real browsers and operating systems, helping you catch styling inconsistencies early and deliver a smooth, reliable user experience.

BrowserStack Live Banner

First-Item Pseudo-Classes

First-item pseudo-classes are CSS selectors designed to style the first occurrence of certain elements, such as the first item in a list, the first line of a paragraph, or the first letter of a sentence. The purpose is to reduce the need for adding extra classes or IDs to elements for simple styling, thereby making your CSS cleaner and more efficient.

The two most popular CSS First-Item Pseudo-Classes selectors are as follows:

:first-child

The :first-child pseudo-class selects an element only if it is the first child of its parent. For example, if you use it to target a <p> element, that paragraph will only be selected if it is the first child within its parent container, regardless of its type.

Syntax:

element:first-child {

    /* Styles */

  }

:first-of-type

The :first-of-type pseudo-class selects the first element of a specific type within its parent, even if other elements come before it. For example, if you use this selector on a <p> tag, it will target the first <p> among its siblings, even if other elements like <div> or <span> appear earlier.

Syntax:

element:first-of-type{

    /* Styles */

  }

How to Use CSS First Item Selector?

It’s essential to understand when to use each first-item selector while writing CSS. If you want to target the very first child of a container, use :first-child. However, if the container has multiple sibling elements of different types, you should use :first-of-type to select the first element of a specific type.

To understand this, here’s an example.

Example 1

<html>

<head>

    <title>Document</title>

    <style>

    p:first-child {

  color: red;

    }

    </style>

</head>

<body>

    <div>

        <p>Paragraph 1</p>  <!-- ✅ Selected -->

        <p>Paragraph 2</p>

      </div>

</body>

</html>

first child

In this case, the ‘Paragraph 1’ is styled because it is the first element of the parent container. However, take a look at the other scenario.

Example 2

<html>

<head>

    <title>Document</title>

    <style>

    p:first-child {

  color: red;

    }

    </style>

</head>

<body>

    <div>

        <span>First Item</span>

        <p>Paragraph 1</p>  <!-- ❌ Not Selected -->

        <p>Paragraph 2</p>

      </div>

</body>

</html>

first child error

Here, ‘Paragraph 1’ is not selected because it is not the first element of the parent container, however, the first child of the container is also not selected because it is not specified in the CSS that you want to style the <span> element.

Here’s the above example using the ‘:first-of-type’ pseudo-class instead of the ‘:first-child’ pseudo-class.

<html>

<head>

    <title>Document</title>

    <style>

    p:first-of-type {

  color: red;

    }

    </style>

</head>

<body>

    <div>

        <span>First Item</span>

        <p>Paragraph 1</p>  <!-- ✅ Selected -->

        <p>Paragraph 2</p>

      </div>

</body>

</html>

first of type

Here, ‘Paragraph 1’ is selected despite not being the very first element among the siblings; however, it is the first element of its kind.

Practical Use Cases and Examples

Now you know how to use First Item Selectors in CSS. Here are a few examples to see their action in real-life scenarios:

Navigation Menus

The use of the First Item selector in the navigation menu comes in handy when you want to style the first element of the navbar, such as the Home link, for easy navigation or highlight the starting point of the navigation, especially in the side menu.

HTML 

  <nav class="navbar">

    <ul class="nav-menu">

      <li><a href="#">Home</a></li>

      <li><a href="#">About</a></li>

      <li><a href="#">Services</a></li>

      <li><a href="#">Portfolio</a></li>

      <li><a href="#">Contact</a></li>

    </ul>

  </nav>

CSS

/* First Item Selector - highlight Home link */

.nav-menu li:first-child a {

  background-color: #ff6347;

  color: #ffffff;

}

.navbar {

  background-color: #1e1e2f;

  padding: 1rem 2rem;

}

.nav-menu {

  list-style: none;

  display: flex;

  justify-content: center;

  gap: 2rem;

}

.nav-menu li a {

  text-decoration: none;

  color: #f0f0f0;

  padding: 0.5rem 1rem;

  border-radius: 8px;

}

navigation menu

Article Layouts

CSS first-item selectors can also be helpful in article layouts. For instance, to emphasize introductory text or decorative elements at the beginning of a paragraph.

In the example below, the :first-of-type pseudo-class targets the first <span> element within the <article> to apply custom styling. This is useful when you want to highlight the first occurrence of a specific tag without using additional classes or IDs.

HTML

  <article>

    <h1>Article</h1>

    <p><span>Introduction </span>While styling the HTML elements using CSS, have you ever wondered how to style certain elements without having to specify any extra classes or ID to prevent cluttering? It is exactly the purpose of the CSS Pseudo Selectors that helps you target certain elements without classes or ID. Certain pseudo-selectors style elements based on their position, state, or type without explicitly marking them in the HTML file.

    </p>

  </article>

CSS

article span:first-of-type {

  font-size: 1.2rem;

  font-weight: bold;

  color: red;

}

article layout

Product Listings

This is seen generally on e-commerce websites, where the first item selector is used to highlight the first item among the products for several reasons, including new arrivals, special offers, and more. Here’s an example demonstrating the use of ‘:first-child’ in the Product Listings.

HTML

 <h1>BStack Demo</h1>

  <section class="product-listing">

    <div class="product">

      <img src="product1.png" alt="Product 1" />

      <h3>Product 1</h3>

      <p>$19.99</p>

      <span class="offer-badge">Special Offer!</span>

    </div>

    <div class="product">

      <img src="product2.png" alt="Product 2" />

      <h3>Product 2</h3>

      <p>$29.99</p>

    </div>

    <div class="product">

      <img src="product3.png" alt="Product 3" />

      <h3>Product 3</h3>

      <p>$39.99</p>

    </div>

    <div class="product">

      <img src="product4.png" alt="Product 4" />

      <h3>Product 4</h3>

      <p>$49.99</p>

    </div>

    <div class="product">

      <img src="product5.png" alt="Product 5" />

      <h3>Product 5</h3>

      <p>$59.99</p>

    </div>

  </section>

CSS – Using First Item Selector 

  /* Offer badge styling */

  .product-listing .product:first-child .offer-badge {

    position: absolute;

    top: 10px;

    left: 10px;

    background-color: red;

    color: white;

    padding: 0.5rem;

    font-weight: bold;

    border-radius: 5px;

    font-size: 0.9rem;

  }

CSS – Styling Elements

h1 {

    text-align: center;

    margin: 2rem 0;

    font-size: 2.5rem;

    color: #333;

  }

 

  .product-listing {

    display: flex;

    justify-content: space-around;

    flex-wrap: wrap;

    gap: 1.5rem;

    padding: 1rem;

  }

 

  .product {

    background-color: white;

    border-radius: 8px;

    width: 200px;

    position: relative;

  }

 

  /* Styling for images */

  .product img {

    width: 100%;

    height: auto;

    border-radius: 8px;

  }

 

  .product h3 {

    margin: 1rem 0;

    font-size: 1.2rem;

    color: #333;

  }

 

  .product p {

    font-size: 1rem;

    color: #007bff;

  }

product listings

Tables and Grids

The use of ‘:first-child’ while designing Tables and Grids for the web is very effective as it styles the header row, or featured items in the table. Here’s an example of how to use ‘:first-child’ highlighting the header of the table.

HTML

 <h2 style="text-align:center;">Students Data</h2>

  <table>

    <tr>

      <th>Name</th>

      <th>City</th>

      <th>College</th>

    </tr>

    <tr>

      <td>Mohit</td>

      <td>Nainital</td>

      <td>COT</td>

    </tr>

    <tr>

      <td>Tanuj</td>

      <td>Haldwani</td>

      <td>COA</td>

    </tr>

    <tr>

      <td>Veer</td>

      <td>Gorakhpur</td>

      <td>AIIMS</td>

    </tr>

  </table>

CSS – Using First Item Selector 

    table tr:first-child {

      background-color: #333;

      color: #fff;

      font-weight: bold;

    }

CSS – Styling Table 

    table {

      width: 60%;

      border-collapse: collapse;

      margin: 2rem auto;

    }

    th, td {

      padding: 12px 20px;

      border: 1px solid #ccc;

      text-align: left;

    }

table and grids

List Groups

A List Group is a set of list items that are grouped to display content under one category that is related. CSS First Item Selectors can be used to style the first item of the List group to highlight the category of related content. Here’s an example:

HTML

  <h2>Top Categories</h2>

  <ul class="list-group">

    <li>🔥 Featured Category</li>

    <li>Electronics</li>

    <li>Fashion</li>

    <li>Books</li>

    <li>Home & Kitchen</li>

  </ul>

CSS – Using First Item Selector 

    ul.list-group li:first-child {

      background-color: #007bff;

      color: white;

      font-weight: bold;

    }

CSS – Styling Elements

    ul.list-group {

      list-style-type: none;

      width: 300px;

Border-radius: 8px;

    }

    ul.list-group li {

      padding: 1rem;

      border-bottom: 1px solid #ddd;

    }

list group

CSS Alternatives to :first-child

Here are a few alternatives to the ‘:first-child’ pseudo selector where you can target elements for styling beyond the first element inside the parent container, among the other sibling elements.

:nth-child(n)

This selector can target any child element beyond the first element. The ‘n’ can be any number, keyword such as odd/even, and formula such as 3n-2 to target elements in any pattern you choose.

HTML

<ul>

  <li>Item 1</li>

  <li>Item 2</li> <!-- ✅ This gets styled -->

  <li>Item 3</li>

</ul>

CSS

    li:nth-child(2) {

  color: red;

  font-weight: bold;

}

nth child

:last-child

This selector is similar to the first-child selector but in reverse order. It targets the last child element inside the parent container.

  li:last-child {

    color: red;

  }

last child

:not(:first-child)

This selector targets every element inside the parent container except the first child element.

  li:not(:first-child){

    color: red;

  }

notfirst child

:only-child

This selector is suitable when the parent container has only one child element, and you want to target that element using a pseudo-selector.

HTML

  <div>

    <p>This gets styled</p> <!-- ✅ Styled because it's alone -->

  </div>


  <div>

    <p>Sibling 1</p>

    <p>Sibling 2</p> <!-- ❌ Not styled -->

  </div>

CSS

  p:only-child {

    color: red;

  }

only child

Common Mistakes to Avoid

Using pseudo-selectors in CSS can significantly boost your efficiency, but it’s important to use them thoughtfully to avoid common pitfalls.

  • Confusing :first-child with :first-of-type:Understand the distinction between these two selectors. :first-child targets an element only if it is the first child of its parent, while :first-of-type is more flexible—it targets the first element of a specific type, even if it’s not the first child overall.
  • Ignoring HTML structure: Pseudo-selectors like :nth-child() or :first-child are heavily dependent on the structure and order of your HTML. For example, :nth-child(2) will no longer target the intended element if you change the order of elements in the DOM.
  • Overusing pseudo-selectors: While pseudo-selectors reduce the need for extra classes or IDs and help keep your code cleaner, overusing them can make your CSS fragile. Small changes in HTML structure can unintentionally break styling tied to these selectors.
  • Overlooking CSS specificity: Remember that inline styles and more specific selectors will override pseudo-selectors. If a style isn’t applying as expected, check for other conflicting rules or inline styles with higher specificity.
  • Neglecting cross-browser testing: Styles applied through pseudo-selectors may behave differently across browsers or devices. Perform cross-browser testing regularly to catch inconsistencies early. Platforms like BrowserStack make this easy by letting you test your CSS on real browsers and devices, ensuring consistent appearance and functionality for all users.

Talk to an Expert

Testing Your Styles Across Browsers

When using CSS pseudo-selectors like :first-child or :first-of-type, it’s important to ensure that your styles behave consistently across all major browsers. While modern browsers mostly adhere to CSS standards, subtle rendering differences can still occur, especially with more complex layouts or legacy browsers.

For instance, a :first-child selector may not apply as expected if the HTML structure changes or if a browser interprets white space or comments differently. That’s why relying solely on local testing is often not enough.

To catch these inconsistencies early, it’s essential to test your website in real browser environments. BrowserStack Live enables real-time testing across a wide range of real browsers and devices, helping you identify and fix inconsistencies early. It also offers access to developer tools for in-browser inspection, support for testing local or staging environments, and a variety of browser–OS combinations,all without the need for setup or virtual machines.

Conclusion

Pseudo-selectors are CSS tools that allow you to target elements based on the element’s position, state, type, or hierarchy and prevent cluttering any extra class or ID. Using pseudo selectors helps maintain a cleaner codebase. There are certain first-item pseudo-selectors, such as first-child and first-of-type, to select elements among the sibling elements inside the parent container.

Other pseudo-selectors, such as ‘:nth-child(n)’, ‘:last-child’, ‘:only-child’, and ‘:not(:first-child)’ are alternatives to First Item Selectors to target elements beyond the first element inside the parent container.

Moreover, pseudo-selectors allow you to create a maintainable codebase; however, overusing them may create a fragile codebase. Since the nature of selectors relies heavily upon the HTML structure, a minor change may disrupt the layout built upon pseudo selectors; therefore, it is essential to use it wisely.

Cross-browser testing is essential to ensure that your styles remain consistent and reliable across different browsers and devices. By combining regular testing with thoughtful use of pseudo-selectors, you can build CSS that is cleaner, more stable, and easier to maintain.

Tags
Manual Testing Real Device Cloud

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord