CSS Selector

AMARJEET KUMARAMARJEET KUMAR
2 min read

CSS selectors help us to give styling to the HTML elements which we want to style.

There are the following types of CSS selectors,

1. CSS Elements Selector

2. CSS Id Selector

3. CSS Class Selector

4. CSS Universal Selector

5.CSS Grouping Selector

1. CSS Elements Selector:- The element selector selects HTML elements based on the element name.

EXAMPLE:- Here All the (h1) elements will be red in color and the font size becomes 30px.

h1{
color: red ;
font-size: 30px ;
}

2. CSS Id selector:-The id of an element is unique within a page, so the id selector is used to select one unique element.

for creating a class selector we have to id attribute. for example - id = "name-of-the-id " is written inside that tag or elements which we want to style.

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

for example- 
#name-of-the-id{
   font-size: 60px ;
   color : #808080;
   background-color: #000000  ;
}

3. CSS Class Selector:- Class selectors can be used multiple times by creating once.

for creating a class selector we have to class attribute. for example - class = "name-of-the-class" is written inside that tag or elements which we want to style.

for access to that class, we will use a dot . on our CSS page.

for example- 
.name-of-the-class{
   font-size: 50px ;
   color : #ffffff;
   background-color: #000000  ;

}

4. CSS Universal Selector:- Universal Selector selects all the HTML elements on the page.

This is denoted by * , and usually this is applied on the top of the CSS page.

EXAMPLE:- The CSS rule below will affect every HTML element on the page: 
* {
  text-align: center;
  color: #808080;
}

5.CSS Grouping Selector:-The grouping selector selects all the HTML elements with the same styling.

Look at the following CSS code h1, h2, and p elements have the same styling.

h1 {
  text-align: center;
  color:  ff0000 ;
}
h2 {
  text-align: center;
  color:  ff0000 ;
}
p {
  text-align: center;
  color:  ff0000 ;
}

Thus it is better to use a single group selector instead of using multiple elements selector. In the grouping selector, all the elements are separated by a comma ,.

Example
h1, h2, p {
  text-align: center;
  color:  ff0000;
}
0
Subscribe to my newsletter

Read articles from AMARJEET KUMAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

AMARJEET KUMAR
AMARJEET KUMAR