Skip to main content

Class Selectors in CSS (Live Playground)

Class selectors in CSS allow you to target and style HTML elements based on their class attributes. This enables you to apply specific styles to elements without affecting others of the same type. In this tutorial, you will learn how to use class selectors effectively, along with sample code and simple explanations.

Using class selectors

To target HTML elements using a class selector, write a period (.) followed by the class name in your CSS file. The styles within the declaration block will be applied to all elements with the specified class attribute.

Example:

CSS
/* Target all elements with the class "highlight" */
.highlight {
background-color: yellow;
font-weight: bold;
}
HTML
<p>This is a normal paragraph.</p>
<p class="highlight">This paragraph has a yellow background and bold text.</p>

In this example, the class selector .highlight targets the paragraph element with the class "highlight" and applies the specified background-color and font-weight styles.

Live Playground, Try it Yourself

Combining class selectors

You can target multiple classes at once by listing the class names as a comma-separated list. The styles within the declaration block will be applied to all elements with the specified class attributes.

Example:

CSS
/* Target all elements with the classes "red-text" and "large-text" */
.red-text,
.large-text {
color: red;
font-size: 24px;
}
HTML
<p class="red-text">This paragraph has red text and a large font size.</p>
<h1 class="large-text">This header has red text and a large font size.</h1>

In this example, the class selectors .red-text and .large-text target elements with the specified class attributes and apply the color and font-size styles.

Live Playground, Try it Yourself

Class selectors with element selectors

Class selectors can be combined with element selectors to target elements of a specific type with a particular class attribute.

Example:

CSS
/* Target all paragraph elements with the class "italic-text" */
p.italic-text {
font-style: italic;
}
HTML
<p class="italic-text">This paragraph has italic text.</p>
<span class="italic-text">This span element is not affected by the p.italic-text rule.</span>

In this example, the selector p.italic-text targets only paragraph elements with the class "italic-text" and applies the specified font-style.

Live Playground, Try it Yourself

Conclusion

In this tutorial, you learned how to use class selectors in CSS to target and style HTML elements based on their class attributes. With this knowledge, you can create versatile and reusable styles that can be applied to specific elements without affecting others of the same type.