What are CSS Rules and Selectors?

Firstly, it’s a good idea to get familiar with what CSS is and how it is used. I have created another article explaining this topic. Here is a link to learn more about CSS and how to use it

CSS Syntax

The style rules in CSS are interpreted by the browser and then applied to the matching elements in your document.

A style rule has three parts: selector, property, and value.

For example, the headline color can be defined as:

h1 { color: blue; }

The selector points to the HTML element you want to style.

One or more declarations are contained in the declaration block and are separated by semicolons.
A colon separates the property name from the value in each declaration.

Type Selectors

Type selectors are the most widely used and simple to comprehend selectors. This selector focuses on certain page element types.

For example, to target all the paragraphs on the page:

p {
  text-align: center;
  color: red;
  font-size: 18px;

Here, all <p> elements on the page will be center-aligned, with a text color that is red and a font-size of 18px applied.

Id and Class Selectors

Id Selectors

Regardless of where they are in the document tree, id selectors let you style an HTML element that has an id attribute. The id of an element is unique within a page, so the id selector is used to select one unique element!

A sample id selector is shown here:

<div id=“unique”>
    <p> This paragraph is in the intro section.</p>
<p> This paragraph is not in the intro section.</p>
#unique {
  color: white;
  background-color: coral;

Use a hash character (#) followed by the element’s id to choose an element with a specified id.

Class Selectors

Similar principles apply to class selectors. The primary distinction between the two is that classes may be used as many times as necessary on a page but IDs may only be applied once per page.

    <p class=“first”>This is a paragraph</p>
    <p> This is the second paragraph. </p>
.first {font-size: 30px;}

Use a period character (.) followed by the name of the class to select elements that belong to that class.
A class or ID name should NOT begin with a number!

The CSS Grouping Selector

All of our selectors up to this point have only focused on a single class, ID, or element. But in CSS multiple elements can be chosen and styled collectively using the CSS grouping selector. Declaring common styles for each element saves time and minimises the amount of code needed. Each selector is separated from the others by a comma.

In this example we have grouped the selectors:

h1, h2, p {
  text-align: center;
  color: orange;

Further reading

For a complete list of all the different types of selectors, see MDN Web Docs CSS selectors reference .

Share this article. Follow me on Twitter for more updates.

What are CSS Rules and Selectors?
Scroll to top

Pin It on Pinterest