CSS Selector

CSS selectors are used to select (or find) the content or HTML Element which we want to style and apply some text formatting.

Types of selectors in CSS.

  • CSS Element Selector
  • CSS Id Selector
  • CSS Class Selector
  • CSS Universal Selector
  • CSS Group Selector

1. CSS Element Selector

The element selector selects the HTML element by name.

p {
  text-align: center;
  color: blue;
}
  Try it Yourself

2. CSS Id Selector

The CSS Id Selector select the id attribute of an HTML element to select a specific element.

Note : The id of an element is unique within a page that's why id selector is used to select one unique element.

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Example :

#paragraph-1{
  text-align: center;
  color:green;
}
  Try it Yourself

3. CSS Class Selector

The class selector selects HTML elements using the specific class attribute.

Selected HTML Element with a specific class  write with a period character(.) followed by the class name.

Example :

  • This example show the <p> tag selected with class="center" will be red color and center aligned.
  • The below selectors show the <h4> tag selected with class="center" will be blue and center aligned.
.center {
  text-align: center;
  color: red;
}
h4.center {
  text-align: center;
  color: blue;
}
  Try it Yourself

4. CSS Universal Selector

The universal selector(*) is used as a wildcard character and it selects all the elements on the pages.

Example :

* {
  text-align: center;
  color: blue;
}
  Try it Yourself

5. CSS Group Selector

The group selector is used to select all the HTML elements with the same style definitions. 

Generally the group selector is used to minimize the code.

If we want to apply same style on one or more html element we should use the css group selector.

Example :

h1, h2, p {
  text-align: center;
  color: red;
}
  Try it Yourself