Following are different types of selectors:
Now, discuss the most basic selectors.
CSS element Selector:
The element selector selects HTML elements by element name.
Here, all <p> elements on the page will be center-aligned, font-size will be 20px and blue text color:
CSS id Selector:
The id selector selects the id attribute of an HTML element to select a perticular element. An id is always unique within the page so it is used to select one, unique element.
It is written with the hash(#) character, followed by the id of the element.
The CSS properties below will be applied to the HTML element with id=”test”:
CSS class Selector:
By using class attribute, the class selector selects HTML elements. To select elements with a perticular class, write a period (.) character, followed by the class name.
Here, all HTML elements with class=”center” will be red background-color and center-aligned:
You also specify that only one specific HTML element should be affected then you should use the element name with class selector.
In this example only elements with class=”center” will be center-aligned and background-color will be red:
CSS Universal Selector:
The universal selector (*) selects all the HTML elements on the page.
Here, the CSS rule below will affect every HTML element on the page:
CSS Grouping Selector:
The grouping selector is used to selects all the HTML elements with the same style definitions.
To minimize the code, grouping selector is useful. Each selector in grouping are seperated by commas.
The CSS code without group selector is as follow:
It will be better to group the selectors, and minimize the code.
In this example we have grouped the selectors from above code.