Class selectors in CSS are a powerful tool for styling specific elements on a web page. They allow you to apply styles to multiple elements with the same class name, providing flexibility and efficiency in your CSS code.
How to use a class selector ?
- Define the class in your HTML: You add a class to an HTML element using the
classattribute. Here’s an example:
<p class="highlight">This paragraph will be highlighted.</p>
- Create the CSS rule with the class selector: In your CSS file, you define the styles for the class using a period (
.) followed by the class name:
.highlight {
color: blue;
font-weight: bold;
background-color: yellow;
}
How it works
- The CSS rule with the
.highlightselector will apply the specified styles to any element in your HTML that has theclass="highlight"attribute. - Multiple elements can share the same class, and they will all inherit the same styles.
Example :
<p class="highlight">This paragraph will be highlighted.</p>
<div class="highlight">This div will also be highlighted.</span>
.highlight {
color: blue;
font-weight: bold;
background-color: yellow;
}
In this example, both the paragraph and the div will be styled with the specified color, font weight, and background color.
Key Points
- Multiple Classes: You can apply multiple classes to a single element to combine different styles. For example:
<p class="highlight important">This paragraph is important and highlighted.</p>
- Specificity: If multiple rules apply to an element, CSS specificity rules determine which rule takes precedence. More specific rules (e.g., those with more selectors or inline styles) override less specific ones.