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
EasyYou are given an HTML document with various elements, including headings (<h1>, <h2>), paragraphs (<p>), and divisions (<div>). Some of these elements have a class attribute. Your task is to use class selectors to style these elements. Follow the steps below:
- Add a
classattribute with the value "blue-text" to the<h1>element and the first<p>element. - Add a
classattribute with the value "large-text" to the<h2>element and the second<p>element. - 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.
- 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.
Cheat sheet
The class selector targets HTML elements based on their class attribute value. Use a period (.) followed by the class name:
.classname {
property: value;
}Example:
.highlight {
background-color: yellow;
color: black;
}This targets all elements with class="highlight" and applies the specified styles.
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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Styling with CSS
5 Colors and Backgrounds
Background ColorHEX ColorsRGB ColorsTransparency with RGBARecap Challenge #1