CSS Class Selector

The CSS Class Selector selects HTML elements using their class attribute. It allows you to apply the same styles to multiple elements without affecting every element of the same type.

A class selector begins with a period (.) followed by the class name. It is useful when you want to style specific headings, paragraphs, buttons, or other HTML elements.

CSS Class Selector Syntax

The syntax for a class selector is:

.classname {
    property: value;
}

For example, .highlight selects elements with class="highlight".

CSS Class Selector Example

<!DOCTYPE html>
<html>
<head>
    <title>CSS Class Selector</title>
    <style>
        .highlight {
            color: blue;
            background-color: lightyellow;
        }
    </style>
</head>
<body>
    <h1 class="highlight">Welcome to Web4Learners</h1>
    <p class="highlight">Learn CSS step by step.</p>
    <p>This paragraph has no class styling.</p>
</body>
</html>

In this example, the heading and the first paragraph receive blue text and a light-yellow background because both use the highlight class. The final paragraph remains unchanged by this rule.

Using One Class on Multiple Elements

You can reuse the same class on as many HTML elements as needed.

<style>
    .button {
        background-color: blue;
        color: white;
        padding: 10px 16px;
    }
</style>

<button class="button">Login</button>
<button class="button">Register</button>

Both buttons receive the same styles.

Using Multiple Classes on One Element

An HTML element can have more than one class. Separate class names with spaces.

<p class="highlight large-text">Welcome to CSS!</p>
.highlight {
    color: blue;
}

.large-text {
    font-size: 24px;
}

The paragraph receives both styles. You can learn more about how CSS rules are written in our CSS Syntax tutorial.

Class Selector vs. Element Selector

An element selector targets all elements of a particular HTML tag, while a class selector targets only elements with a specified class.

For example, p selects all paragraphs, whereas .highlight selects only elements assigned the highlight class.

Explore our CSS Element Selector tutorial to understand the difference.

Class selectors are especially useful for creating reusable, consistent designs across a website.