CSS class selector
The selector is one of the important things when we are defining the set of rules for styling some element(s) in the web page. The class selector is one of the selectors. Well, if you are already familiar, we have an attribute in HTML, which is class, and the class attribute can be used to group several elements into one class. This is just like when several students can be there in a class, we can have several elements belonging to one class, on the HTML web page. On the other hand, the id has to be unique for the element, and should not repeat on the web page.
In simple terms, we are telling that we want to apply the mentioned set of rules to all the elements belonging to that particular class. Now, let’s get started with learning, how can we use the class selector.
To use the class for styling a particular class of elements, you just need to mention the class. To mention the class, you need to use the (.) dot character(also referred to as the period character) and then you have to give the class name immediately.
Unlike id, you can have the same class name for different elements. Now, we are going to have a look at an example, where we are going to create some div elements, which are going to belong to some class, and some other divs, which are not going to belong to some class. Now, when we are going to use the class selector for specifying the style for the class elements, the other elements are not going to be styled. Have a look –
As you can see, there are some divs, which belong to the class mydiv, and some other divs, which do not belong to that class. So, when we are specifying the styles for the elements that belong to the class mydiv, the other divs won’t be styled. Let’s have a look at the output now –
As you can see, only those elements, which belong to the class mydiv, are styled, and the others are not styled. So, whenever we need to style some elements that belong to some particular class, we can just make use of the class selector. Remember that the class selector starts with the “.” sign (we also call it a period character). Also, there can be multiple elements belonging to the same class.