Categories
Web development

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

CSS :only-child and :only-of-type selectors

:only-child

The CSS :only-child selector matches an element that is the only child of its parent (the parent element has no other element children).

Syntax:

 :only-child {
  CSS declarations;
} 

Example:

Specify a font color for every element that is the only child of its parent:

<!DOCTYPE html>
<html>
<head>
<style> 
.example p:only-child {
  color: #2a9d8f;
}
</style>
</head>
<body>

<div class="example"><p>This is a paragraph.</p></div>

<div class="example"><p>This is a paragraph.</p><p>This is a paragraph.</p></div>

</body>
</html>

Output:

This is a paragraph.

This is a paragraph.

This is a paragraph.


:only-of-type

The CSS :only-of-type selector matches an element that is the only child of its type, of its parent (the parent element has no other element children).

Syntax:

:only-of-type {
  CSS declarations;
}

Example1:

<!DOCTYPE html>
<html>
<head>
<style> 
.example p:only-of-type {
  color: #2a9d8f;
}
</style>
</head>
<body>

<div class="example"><p>This is a paragraph.</p></div>

<div class="example"><p>This is a paragraph.</p><p>This is a paragraph.</p></div>

</body>
</html>

Output:

This is a paragraph.

This is a paragraph.

This is a paragraph.


Example2:

<!DOCTYPE html>
<html>
<head>
<style> 
.example h4:only-of-type {
  color: #2a9d8f;
}
</style>
</head>
<body>

<div class="example">
<h4>This is a heading.</h4>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>

</body>
</html>

Output:

This is a heading.

This is a paragraph.

This is a paragraph.

Note: The CSS :only-child selector selects an element that is the only child of a parent. That means only one element within its container (parent). The CSS :only-of-type selector selects an element if that is the only child of a particular type within its container (parent). So in the case of :only-of-type selector, having other children(of different types) in a container is allowed.

Enjoy coding!