Group Selectors
Part of the Styling with CSS section of Coddy's HTML journey — lesson 14 of 76.
The group selector is used to select multiple HTML elements and apply the same styles to all of them. This is particularly useful when you want to apply a common set of styles to different elements without having to write separate rules for each element. By grouping selectors, you can write more concise and efficient CSS code.
To use a group selector, you list the selectors you want to group, separated by commas (,). Here's the basic syntax:
selector1, selector2, selector3 {
property: value;
}For example, let's say you want to apply the same text color and font size to all <h1>, <h2>, and <p> elements. You can use a group selector like this:
h1, h2, p {
color: blue;
font-size: 16px;
}In this example, the group selector targets all <h1>, <h2>, and <p> elements. The declarations set the text color to blue and the font size to 16 pixels for all these elements.
You can group any type of selectors, including type selectors, class selectors, and ID selectors:
h1, .highlight, #intro {
background-color: yellow;
}Challenge
EasyYou are given an HTML document with various elements, including headings (<h1>, <h2>), paragraphs (<p>), and a division (<div>). Your task is to use a group selector to style these elements. Follow the steps below:
- Write a CSS rule using a group selector that targets all
<h1>and<h2>elements. Set the text color of these elements to red. - Write a CSS rule using a group selector that targets all
<p>elements and the<div>element. Set the background color of these elements to lightgray and the font size to 18 pixels.
Cheat sheet
The group selector allows you to apply the same styles to multiple HTML elements by separating selectors with commas (,):
selector1, selector2, selector3 {
property: value;
}Example grouping element selectors:
h1, h2, p {
color: blue;
font-size: 16px;
}You can group any type of selectors (type, class, ID):
h1, .highlight, #intro {
background-color: yellow;
}Try it yourself
<html>
<head>
<title>Group Selectors</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>
<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