CSS Selectors

CSS selectors are used to select the content you want to style. They are used to “find” (or select) the HTML elements you want to style.

In this chapter you will learn about simple or basic CSS selectors. It is used to select the HTML elements based on their element name, id, attributes, etc.

CSS Element Selector

The element selector selects HTML elements based on the element name.

Syntax

element_name {
    // CSS Property
}

Example

In below example all <p> elements on the page will be center-aligned, with a red text color.

p {
  text-align: center;
  color: red;
}

CSS Id Selector

The id selector uses the id attribute of an HTML element to select a specific element. An id is always unique within the page so it is chosen to select a single, unique element.

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

Syntax

#id_name { 
    // CSS Property
}

Example

In below example HTML element with id=”para1″ on the page will be center-aligned, with a red text color.

#para1 {
  text-align: center;
  color: red;
}

CSS Class Selector

The class selector selects HTML elements with a specific class attribute.

A class name should not be started with a number.

To select elements with a specific class, write a period (.) character, followed by the class name.

Syntax

.class_name {
    // CSS Property
}

Example

In below example HTML element with class=”center” on the page will be center-aligned, with a red text color.

.center {
  text-align: center;
  color: red;
}

CSS Class Selector for specific element

You can also specify that only specific HTML elements should be affected by a class. If you want to specify that only one specific HTML element should be affected then you should use the element name with class selector.

Example

In below example only <p> elements with class=”center” on the page will be center-aligned, with a red text color.

p.center {
  text-align: center;
  color: red;
}

CSS Universal Selector

The universal selector (*) selects all HTML elements on the page. The universal selector is used as a wildcard character. It selects all the elements on the pages. It also selects all elements which are inside under another element.

Syntax

* {
    // CSS property
} 

Example

The CSS rule below will affect every HTML element on the page.

*{
  text-align: center;
  color: red;
}

CSS Group Selector

The grouping selector is used to select all the elements with the same style definitions. It is used to minimize the code. Commas are used to separate each selector in grouping.

CSS code without group selector.

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

CSS code with group selector.

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