CSS sets the style of the first element

CSS Set First Element Style

CSS Set First Element Style

In front-end development, we often need to set the style of some specific elements, such as the first element. CSS selectors make this easy. This article will detail how to style the first element using CSS, along with some sample code.

1. Using the :first-child Selector

:first-child is a pseudo-class selector in CSS that selects the first child of a parent element. By using this selector, we can easily style the first child element.


The sample code is as follows:

ul li:first-child {
color: red;
font-weight: bold;
}

The above code selects the first li element under the ul element and sets its text color to red and font to bold.

2. Using the :first-of-type Selector

:first-of-type is another pseudo-class selector in CSS that selects the first child element of a specific type under a parent element. Unlike :first-child, :first-of-type selectors select the first child element of any specified type.

The sample code is as follows:

div p:first-of-type {
background-color: lightgray;
padding: 10px;
}

The above code selects the first p element under the div and sets its background color to light gray and padding to 10 pixels.

3. Combining with Other Selectors

We can also combine the :first-child or :first-of-type selectors with other selectors for more flexible styling.

The sample code is as follows:

ul li:first-child a { 
text-decoration: none; 
color: blue; 
}

div p:first-of-type span {
font-style: italic;
color: green;
}

The above code selects the a element within the first li element under the ul and sets its text color to blue without underlining; and selects the span element within the first p element under the div and sets its text to italic and green.

4. Conclusion

Through this article, we’ve learned how to use CSS selectors to style the first element. Both the :first-child and the :first-of-type selectors can help achieve this goal. In actual development, we can choose the appropriate selector based on the specific situation and combine them with other selectors for more flexible styling.

Leave a Reply

Your email address will not be published. Required fields are marked *