What is Selector

Selectors are one of the most important aspects of CSS as they are used to select elements on a web page so that they can be styled. You can define selectors in various ways.

Universal Selector

The universal selector, written as * i.e. asterisk or star symbol, matches every single element on the page. The universal selector may be omitted if other conditions exist on the target element. This selector is often used to remove the default margins and paddings from the elements for quick testing purpose.

    
    * {

        margin: 0;

        padding: 0;

    }

Element Type Selector

An element type selector matches every instance of the element in the document tree with the corresponding element type name.

p {

color: blue;

}

The style rules inside the p selector will be applied on every

element in the document and color it blue, regardless of their position in the document tree.

Id Selectors

The id selector is used to define style rules for a single or unique element.

The id selector is defined with a hash sign (#) immediately followed by the id value.

#error {

color: red;

}

This style rule renders the text of an element in red, whose id attribute is set to error.

Class Selectors

The class selectors can be used to select any HTML element that has a class attribute. All the elements having that class will be formatted according to the defined rule.

The class selector is defined with a period sign (.) immediately followed by the class value.

.blue {

color: blue;

}

The above style rules renders the text in blue of every element in the document that has class attribute set to blue. You can make it a bit more particular. For example:

p.blue {

color: blue;

}

The style rule inside the selector p.blue renders the text in blue of only those

elements that has class attribute set to blue, and has no effect on other paragraphs.