The first element of the CSS class name
First element of CSS class name
In HTML and CSS, we often use class names to select specific elements for styling. In some cases, we may need to select the first element of a class name for special styling. This article details how to use CSS to select the first element of a class name, and provides some code examples.
1. Using the :first-of-type Selector
In CSS, we can use the :first-of-type
selector to select the first element of a certain type. When combined with a class name selector, we can select the first element of a class name.
.my-class:first-of-type {
/* Set styles here */
}
For example, if we have the following HTML code:
<div class="my-class">first element</div>
<div class="my-class">second element</div>
<div class="my-class">third element</div>
We can use the :first-of-type
selector to select the first element with the .my-class
class:
.my-class:first-of-type {
color: red;
}
This will set the text color of the first .my-class
element to red.
2. Sample Code
Here is a complete sample code that demonstrates how to select the first element of a class name:
<!DOCTYPE html>
<html Tutorial">html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First element of CSS class name</title>
<style>
.my-class:first-of-type {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div class="my-class">First element</div>
<div class="my-class">Second element</div>
<div class="my-class">Third element</div>
</body>
</html>
3. Run Result
Through the above sample code, we can see that the text color of the first .my-class
element changes to red and is bold. This is because we used the :first-of-type
selector to select the first element of a class name and set the corresponding style.
Through this article, we learned how to use CSS to select the first element of a class name.