CSS :only-of-type

The CSS :only-of-type pseudo-class is used when we need to select an element that is the only child element of a specified type of its parent element. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:only-of-type {font-weight: bold; font-style: italic; color: sienna;}
   </style>
</head>
<body>

   <p>This is para one (the only para inside BODY).</p>
   <div>
      <p>This is para one, inside DIV one.</p>
      <p>This is para two, inside DIV one.</p>
   </div>
   <div>
      <p>This is para one, inside DIV two (the only para inside this DIV).</p>
   </div>
   
</body>
</html>
Output

This is para one (the only para inside BODY).

This is para one, inside DIV one.

This is para two, inside DIV one.

This is para one, inside DIV two (the only para inside this DIV).

In the above example, the following code:

p:only-of-type

is a CSS selector that targets a paragraph element that is the only element of its type within its parent element. In this case, it will select the first p element within the body element but not the other p elements within the div elements.

Now the following CSS code:

font-weight

is a CSS property that sets the weight or thickness of the font within an element. In this case, the font weight is set to "bold".

Then the following CSS code:

font-style

is also a CSS property that sets the style of the font within an element. In this case, the font style is set to "italic".

Finally, the following CSS code:

color

is a CSS property that sets the color of the text within an element. In this case, the color is set to "sienna".

CSS :only-of-type syntax

The syntax of the :only-of-type pseudo-class in CSS is:

selector:only-of-type {
   // styles to apply
}

The selector represents the element or group of elements that the selector is targeting. After that, the :only-of-type pseudo-class selector is appended to the selector, followed by the styles to be applied to the selected element.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!