CSS Selectors

CSS selectors are HTML tags to which a CSS style is applied. This could be any tag like < p > or < h1 > etc. These are patterns used to select the HTML tags that you want to style. These patterns may range from simple element names to rich contextual patterns.

CSS rule

In the following sections, looking at how you can use different types of a selectors to specify which elements a style sheet rule can apply to.

CSS selectors

Element Selector or Type Selector

The CSS element Selector or the type selector matches occurrences of those tags specified in the list.

CSS type selector


p { font-size:32px; }

Above CSS code sets all paragraph font size as 32.

<html> <head> <style type="text/css"> p {font-size:32px;} </style> </head> <body> This line displayed in default font size <p> Line formated with element selector </p> </body> </html>

When you run the above HTML code in the browser you can see first line in default font size and the lines inside < p > element is font size is changed to 32px.


CSS element selector

Universal selector

The universal selector set a value for all elements in the HTML document.

CSS universal selector


* {font-size:14px;}

The above CSS code set font size =14px to the whole HTML document. The universal selector is an asterisk (*) and it acts like a wildcard and matches all element types in an HTML page. In some situations you want to apply a rule to all elements in an HTML page then you can use this selector.

<html> <head> <style type="text/css"> * {font-size:32px;} </style> </head> <body> Universal selector set all font size as 22 in this document </body> </html>

When you run the above HTML code in the browser you can see all font size set to 32px.

Grouped Selectors

Whenever a situation that you need to apply the same style property to a number of selectors, then you can group those selectors into one rule by separating them with commas. The selector rule has the same effect to more than one selector at a time.


h1 {color: #FF0066;} h2 {color: #FF0066;} p {color: #FF0066;}

Instead of above multiple selectors you can group them as follows:

h1,h2,p {color: #FF0066;}

You group selectors so that you don`t have to repeat the same declarations for each selector.

The main advantage of Grouped Selector is that you can edit these elements properties just by a single update.

<html> <head> <style type="text/css"> h1,h3,p {color: #FF0066;} </style> </head> <body> <h1>Grouped Selectors</h1> <h2>This one not in the group</h2> <h3>This elements also grouped</h3> This line is not in the grouped selector. <p>This paragraph also in the group </p> </body> </html>

Output :

CSS grouped selectors

From the above image, you can understand how the Grouped Selector is styling an HTML document.