CSS selectors are used to find or select the HTML elements one want to style. These can be divided in to five broad categories as follows:
- Simple selectors (select elements based on element's name, id, class)
- Combinator selectors (select elements based on a specific relationship between them)
- Pseudo-class selectors (select elements based on a certain state)
- Pseudo-elements selectors (select and style a part of an element)
- Attribute selectors (select elements based on an attribute or attribute value)
In this article, the prime focus will be on the simple selectors.
The element selector
In order turn the colour of all paragraphs appearing on a web page to red, one could select all p elements with following code:
1p { 2 color: red; 3} 4
The class selector
In order turn the colour of all html elements to which a class of red, for example, is given in the markup, one could select all elements with the class of red and change their colour with following code:
1.red { 2 color: red; 3} 4
The id selector
In order turn the colour of an html element to which an id of red, for example, is given in the markup, one could select that element with the id of red and change its colour with following code:
1#red { 2 color: red; 3} 4
The universal selector
There may be situations when one needs to apply particular styles to all elements in a web page. That is usually the case when one wants to remove margin and padding property from all items as all elements have margin and padding property by default which are set by the browsers. In order to remove that margin and padding, one can use the universal selector in CSS with below code:
1* { 2 margin: 0; 3 padding: 0; 4} 5
The grouping selectors
There may be situations when one wants to apply exact styles to more than one elements or classes on a page. In that case, one can group them together separated by a comma and apply the styles all at one. Have a look at below example:
1h1, 2h2, 3h3, 4p { 5 color: red; 6} 7
Conclusion
The key take away from this article are as follows:
- There are different kinds of selectors in CSS like elements, classes, etc.
- One can group multiple elements together separated by a comma to apply same styles to all these elements.
- One can use universal selector to apply particular styles to all items on a page.