0
0
CSSmarkup~5 mins

Class selectors in CSS

Choose your learning style9 modes available
Introduction

Class selectors let you style many elements the same way by giving them a shared name. This helps keep your webpage looking neat and consistent.

You want to make all buttons on your page blue without changing each one separately.
You want to highlight certain paragraphs with a special background color.
You want to apply the same font style to multiple headings.
You want to add a red border to some images but not all.
You want to change the text color of specific list items.
Syntax
CSS
.className { property: value; }
Start the class selector with a dot (.) followed by the class name.
You can use the same class on many HTML elements to style them alike.
Examples
This styles all elements with class 'highlight' to have a yellow background.
CSS
.highlight { background-color: yellow; }
HTML element using the 'highlight' class to get the yellow background.
CSS
<p class="highlight">This paragraph is highlighted.</p>
Styles all elements with class 'button' to look like blue buttons with white text.
CSS
.button { color: white; background-color: blue; padding: 0.5rem 1rem; border-radius: 0.25rem; }
Sample Program

This webpage shows two paragraphs and two buttons. The paragraph with class 'highlight' has a yellow background and bold text. The button with class 'button' is styled with white text on blue background and rounded corners. The other paragraph and button have default styles.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Class Selector Example</title>
  <style>
    .highlight {
      background-color: yellow;
      padding: 1rem;
      font-weight: bold;
    }
    .button {
      color: white;
      background-color: blue;
      padding: 0.5rem 1rem;
      border-radius: 0.25rem;
      border: none;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <p>This paragraph is normal.</p>
  <p class="highlight">This paragraph is highlighted with a yellow background.</p>
  <button class="button">Click Me</button>
  <button>Normal Button</button>
</body>
</html>
OutputSuccess
Important Notes

You can add multiple classes to one element by separating them with spaces, like class="button highlight".

Class names should be meaningful and easy to remember.

Class selectors are case sensitive in CSS, so .Button and .button are different.

Summary

Class selectors start with a dot and target elements with that class name.

They let you style many elements the same way easily.

Use class selectors to keep your webpage consistent and organized.