How to add styles to the first child element of a specific type in CSS
In this article, we’ll learn how to use CSS to style the first child of an element of a specific type. We’ll first explain how to use the :first-child pseudo-class selector, and then provide some examples to illustrate the details.
Read more: CSS Tutorial
What is the :first-child pseudo-class selector?
In CSS, the :first-child pseudo-class selector is used to select the first child of a specified element. The selector syntax is: :first-child, and it can be used with any CSS selector, such as element selectors, class selectors, and ID selectors.
How do I add styles to the first child of a specific type of element?
To style the first child of an element of a specific type, we need to use the :first-child pseudo-class selector in conjunction with an element selector.
For example, if we want to style the first child of all paragraphs (
tags), we can use the following CSS code:
p:first-child {
color: red;
font-weight: bold;
}
The above code will select the first child of all paragraphs, set their text color to red, and apply a bold font style.
Examples
Let’s take a closer look at some examples to learn how to style the first child of an element of a specific type.
Example 1: Adding Styles to the First Child of a List
Suppose we have an unordered list (
<
ul> tag), we want to style the first child element of each list item (
- tag). We can use the :first-child pseudo-class selector and element selectors to achieve this.
<ul> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul>
li:first-child { color: blue; font-weight: bold; }
The above code will select the first child element of each list item (i.e., the first list item) and apply styles to its text, setting its text color to blue and applying bold styling.
Example 2: Styling the First Child of a Table
Suppose we have a table with multiple rows and columns, and we want to style the first cell (the
tag) in each row. We can achieve this using the :first-child pseudo-class selector and an element selector.
<table> <thead> <tr> <th>Name</th> <th>Age</th> <th>Gender</th> </tr> </thead> <tbody> <tr> <td>Zhang San</td> <td>25</td> <td>Male</td> </tr> <tr> <td>John Doe</td> <td>30</td> <td>Female</td> </tr> </tbody> </table>
td:first-child { background-color: yellow; }
The above code will select the first cell in each row (i.e. the name column) and set its background color to yellow.
Summary
In this article, we learned how to use the :first-child pseudo-class selector to style the first child of a specific type of element. We demonstrated how to style the first child of a list and the first child of a table. I hope this article has helped you understand how to use CSS selectors. By making full use of CSS selectors, you can easily add various styles to different elements on a page.