html

How to group multiple HTML elements in CSS

CSS is all about the styling of web pages, websites, HTML documents, etc. therefore it offers a lot of styling tools like selectors, CSS properties, etc. The selectors are the initial component of CSS rules, the rules that target some HTML element(s) and style it according to some specific CSS properties.

In CSS, selectors are classified into five categories i.e. basic selectors, combinatory selectors, pseudo-class selectors, and attribute selectors. The basic category consists of an element selector, class selector, id selector, universal selector, and grouping selector. You can learn more about the basic selectors in our tutorial CSS selectors.

This write-up will explain the following terminologies:

  • What is a grouping selector in CSS?
  • Basic Syntax of grouping selector.
  • How to group multiple HTML elements using a grouping selector.

Let’s get started with the basic understanding of grouping selector:

What is a Grouping Selector in CSS

The grouping selector targets the multiple HTML elements and styles them simultaneously. It concise the code and reduces the extra bit of effort. While selecting/grouping more than one HTML element, we have to separate each HTML element with a comma.

Syntax

Let’s have a look at the following snippet to understand the syntax of the grouping selector:

In the above figure, p, h2, h3, and footer are HTML elements grouped together to be styled.

Let’s move one step further to understand the concept of grouping selector with the help of an example:

How to group multiple HTML elements using a grouping selector

Let’s take a look at the below-given example to understand how to implement a unique style on a group of different HTML elements:

Example This example has different HTML elements i.e. <h1>, <h2>, and <p>. We have to style all these elements in italic font style, with the royal blue background color.

HTML

<h1>linuxhint.com</h1>
<p> Hi! welcome to linuxhint.com </p>
<h2>Grouping Selector</h2>
<p> this is an example of grouping selector </p>

CSS

h1, h2, p {
  background-color: royalblue;
  font-style: italic;
}

The above-given code grouped three elements, implement the same style on all the elements, and as a result, we will get the following output:

It verifies that all the elements implements the same style and the grouping selector is working properly.

Conclusion

To implement a grouping selector all you have to do is simply write all the element’s names you want to style and add a comma between each element. In this way, the specified style will be implemented to each targeted element simultaneously. This write-up covers every aspect of grouping selectors, starting from what is group selector and how to use it.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.