Categories
Web development

CSS :first-child Selector

CSS :first-child selector

The CSS :first-child selector selects the specified selector, only if it is the first child of its parent.

Syntax:

:first-child {
  CSS declarations;
} 

Example:

<!DOCTYPE html>
<html>
<head>
<style>
h4:first-child {
  color: #e76f51;
}
</style>
</head>
<body>
    
<h4>CSS :first child example (This heading is the <b> first child</b> of its parent (body)).</h4>

<h4>This heading is not the first child of its parent.</h4>


<div>
  <h4>This heading is the <b> first child</b> of its parent (div)).</h4>
  <h4>This heading is not the first child of its parent.</h4>
</div>

</body>
</html>

Output:

CSS :first child example (This heading is the first child of its parent (body)).

This heading is not the first child of its parent.

This heading is the first child of its parent (div)).

This heading is not the first child of its parent.


To style HTML elements you can combine the :first-child selector with CSS classes and other CSS selectors:

Example:

<!DOCTYPE html>
<html>
<head>
<style>
.example {
display: flex;
    }

.circle {
width:100px;
height: 100px;
background-color: #2a9d8f;
border-radius:50%;
margin-right:20px;
    }
    
.circle:first-child {
  border-radius:10px;
}
    
.circle:first-child:hover {
  background-color: #e76f51;
    }
</style>
</head>
<body>
    
<div class="example">
    <div class="circle"></div><!-- This is a first child of its parent -->
    <div class="circle"></div>
    <div class="circle"></div>
</div>

</body>
</html>

Output:

Enjoy coding!

Read also:

CSS :hover and :active selectors

CSS :only-child & :only-of-type Selectors

CSS :empty Selector