As the name suggests, CSS Selectors are used to select the CSS elements on which you want to apply the styles.
Say for example, you want to apply styles on a p element. i.e. Change the color of the contents of p element to red.
In that case you can use the element selector for the p element.
<html> <head> <style> p { color: red; } </style> </head> <body> <p>This is the first paragraph</p> </body> </html>
So, if you look at the above code. We have defined the selector for the p element.
<style> p { color: red; } </style>
And the contents of the p element changes to red.
<p>This is the first paragraph</p>
But the CSS Selectors are not restricted to element selectors. We have other CSS Selectors as well.
Let us see them in detail.
CSS Simple Selectors are used to select the HTML elements using the element name, class name or id.
We have already explained CSS element selectors. Let us look at CSS Simple Selectors using class name and id.
CSS Class Selectors selects the HTML elements based on the class name. The class name needs to be specified with a dot(i.e. '.') in front of it.
<html> <head> <style> .my_class { color: red; } </style> </head> <body> <p class="my_class">This is the first paragraph</p> </body> </html>
So, in the above example we have defined a paragraph with the p element. Also defined a class with name my_class.
<p class="my_class">This is the first paragraph</p>
Now, we have used the class name(i.e. my_class) to apply styles to the paragraph.
<style> .my_class { color: red; } </style>
And the color of the contents of the paragraph changes to red.
CSS id Selectors selects the HTML elements based on the id. The id needs to be specified with a hash(i.e. '#') in front of it.
<html> <head> <style> #my_id { color: red; } </style> </head> <body> <p id="my_id">This is the first paragraph</p> </body> </html>
In the above example, we have a paragraph with id myid.
<p id="my_id">This is the first paragraph</p>
And to apply styles to it, we have specified the id with a hash(i.e. '#') in front of it.
<style> #my_id { color: red; } </style>
In the next tutorials, we will be explaining the CSS Attribute Selectors, Combinator Selectors, Pseudo Element Selectors and Pseudo Class Selectors.