Categories
Web development

CSS :first-of-type Selector

CSS :first-of-type Selector

The CSS :first-of-type selector allows you to match the first child of an element within its container.

Syntax:

:first-of-type {
  CSS declarations;
} 

Example1:

<!doctype html>
<html>
<head>
<style>
.example-1 p:first-of-type {
        color: #2a9d8f;
    }
</style>
</head>

<body>
<div class="example-1">
 <h4>Example:</h4>
 <p>This is the first paragraph.</p>
 <p>This is the second paragraph.</p>
 <p>This is the third paragraph.</p>
</div>
</body>
</html>

Output:

Example:

This is the first paragraph.

This is the second paragraph.

This is the third paragraph.


Example2:

<!doctype html>
<html>
<head>
<style>
.example-2 div:first-of-type {
        color: #2a9d8f;
        font-size:25px;
    }
</style>
</head>

<body>
<div class="example-2">
 <h4>Example:</h4>
 <div>This is the first div.</div>
 <div>This is the second div.</div>
 <div>This is the third div.</div>
    </div>
</body>
</html>

Output:

Example:

This is the first div.
This is the second div.
This is the third div.

Enjoy coding!