CSS Selectors

❮ Previous Home Next ❯

To understand CSS rules, you must first master selectors.




What is Selector?

The CSS selectors are used to select the HTML elements to style.

And CSS selectors can be divided in five categories:




Selectors are one of the most important aspects of CSS as they allow you to target specific elements on your web page in various ways so that they can be styled.

Several types of selectors are available in CSS, let's take a closer look at them:




The CSS element Selector

The element selector selects all element of the name specified in the rule.

The simplest rules can be applied to all occurrences of a particular element, such as <p>.

Example

h1 { 
  background-color: red;
}

p { 
  background-color: green;
}

div { 
  background-color: pink;
}



The CSS id Selector

The #id selector selects any tag with an id attribute set.

Example

#example1 { 
  background-color: red;
}

#example2 { 
  background-color: green;
}

#example3 { 
  background-color: pink;
}

Note: The id attributes must have unique values, an ID selector can never match more than one element in a document.







The CSS class Selector

The .class selector selects all tags with the specified class value.

Example

.example1 { 
  background-color: red;
}

.example2 { 
  background-color: green;
}

.example3 { 
  background-color: pink;
}

Note: Whitespace characters can’t appear after the period, or between an element type selector, or explicit universal selector, and the period.




The CSS Universal Selector

The *(universal) selects all elements

Example

* { 
  background-color: red;
}



The CSS Grouping Selector

The CSS grouping selector applies the same rules to a group of tags.

Example

h1, div, p  { 
  background-color: red;
}

Note: Don’t leave a comma after the last selector in the group.




Note:See all CSS selectors reference

❮ Previous Home Next ❯