Skip to main content

CSS Selectors

CSS Class Selector

Written by Updated

Apply reusable styles with class selectors and build names that describe components, variants, and states without depending on page structure.

The CSS Class Selector is used to style specific HTML elements that have a class attribute.
Unlike the element selector, which targets all elements of a type, the class selector allows you to apply styles to only selected elements, giving you more control and flexibility.

A class can be used multiple times on a page.

Class selectors are defined using a dot (.) followed by the class name. The supporting concepts are explained in CSS Element Selector and CSS ID Selector.

Class Selector Syntax

css

.classname {
    property: value;
}

Class Selector Example

css

.highlight {
    color: red;
    font-size: 20px;
}

👉 This will apply styles to all elements with class="highlight".

Attributes

PropertyDescriptionExample
colorSets text colorcolor: blue;
backgroundSets background colorbackground: yellow;
font-sizeSets text sizefont-size: 18px;
paddingAdds inner spacingpadding: 10px;
borderAdds borderborder: 1px solid black;

Classes as stable styling hooks

A class can be shared by many elements and combined with state or variant classes. Keep selectors shallow so the class continues to work when markup is reorganized. Names should describe a component role or durable state rather than a temporary visual detail. This makes the stylesheet easier to search, override, and reuse without coupling it to one page hierarchy.

Example

Complete Example of CSS Class Selector

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS Class Selector</title>
    <style>
        .highlight {
            color: red;
            font-size: 20px;
        }

        .box {
            background: lightgray;
            padding: 10px;
            border: 1px solid black;
        }
    </style>
</head>
<body>

    <h1 class="highlight">Class Selector Example</h1>

    <p class="highlight">This paragraph is highlighted.</p>

    <p>This paragraph is normal.</p>

    <div class="box">This is a styled box.</div>

</body>
</html>

Browser Support

Feature
Chrome
Edge
Firefox
Safari
Class selector11211

Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.

Notes

  • Class selector starts with a dot (.)
  • A class can be used on multiple elements
  • An element can have multiple classes (e.g., class="box highlight")
  • Class names should not start with numbers
  • Best practice: use meaningful and reusable class names

Conclusion

The CSS Class Selector provides flexibility and control by allowing you to style specific elements without affecting others. It is one of the most commonly used selectors in modern web development.