Menu
CoddyTech

Class Selector

Part of the Styling with CSS section of Coddy's HTML journey. Lesson 12 of 76.

The class selector is used to select HTML elements based on the value of their class attribute. It allows you to apply the same styles to multiple elements across your document. Class selectors are particularly useful when you want to style a group of elements in the same way, regardless of their tag names.

To target elements with a specific class in your CSS, you use a period (.) followed by the class name. Here's the basic syntax for using a class selector:

.classname {
    property: value;
}

For example:

.highlight {
    background-color: yellow;
    color: black;
}

In this example, the class selector .highlight targets all elements with the class "highlight". The declarations set the background color to yellow and the text color to black for these elements.

challenge icon

Challenge

Easy

You are given an HTML document with various elements, including headings (<h1>, <h2>), paragraphs (<p>), and divisions (<div>). None of them has a class yet: you will add the class attributes first, then style the elements with class selectors. Follow the steps below:

  1. Add a class attribute with the value "blue-text" to the <h1> element and the first <p> element.
  2. Add a class attribute with the value "large-text" to the <h2> element and the second <p> element.
  3. Write a CSS rule using a class selector that targets all elements with the class "blue-text". Set the text color of these elements to blue.
  4. Write a CSS rule using a class selector that targets all elements with the class "large-text". Set the font size of these elements to 24 pixels.

Try it yourself

<html>
<head>
    <title>Class Selector</title>
    <style>
        /* Write CSS rules here */
    </style>
</head>
<body>
    <h1>This is a main heading</h1>
    <h2>This is a subheading</h2>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <div>This is a division.</div>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Styling with CSS

Practice on your own: Web playground