CSS for Web Development

0% completed

Previous
Next
Class Selectors

CSS class selectors let you style elements by adding a class attribute to them. This gives you more control and flexibility since you can apply the same style to multiple elements even if they are different types. Using class selectors helps you avoid repeating the same style rules.

You add a class attribute to an HTML element and then define a CSS rule for that class. This makes it easy to maintain and update your styling without affecting other elements that do not belong to that class.

Syntax

Follow below syntax to add class selectors in CSS code.

.selector { property: value; }

Explanation:

  • .selector: The period (.) before the name indicates that it's a class selector.
  • property: The specific aspect of the element you want to style (e.g., color, font-size).
  • value: The new setting for that property (e.g., red, 16px).

Example 1: Styling Elements with a Class

In this example, we will style elements that have the class highlight. The example demonstrates how to change the text color and background color for these elements.

HTML

. . . .

Explanation:

  • CSS Rule for the .highlight Class:
    • Selector: The .highlight selector applies to all elements that include class="highlight".
    • Properties:
      • Color: Text is changed to white.
      • Background Color: The background is set to dark blue.
      • Padding: Adds space around the content for better appearance.
  • Outcome: Only the elements with the highlight class will have the defined styles, while others remain unaffected.

Example 2: Applying Multiple Classes

In this example, we will use multiple classes on a single element. One class sets the text color, and another sets the font size. This shows how class selectors can be combined to create a more flexible design.

HTML

. . . .

Explanation:

  • CSS Rules for Multiple Classes:
    • .text-red: This rule changes the text color to red.
    • .large-text: This rule increases the font size to 24 pixels.
  • Usage of Multiple Classes:
    • The <h1> element uses both text-red and large-text classes to combine the styles.
    • Other paragraphs use either one of the classes, showing how you can apply styles selectively.

This lesson on class selectors shows how to apply styles to elements that share the same class. It also demonstrates how to combine multiple classes, giving you the flexibility to build adaptable and organized styles for your web page.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next