Class Selector in CSS
- W3C defines Class as “Specific Group of Elements“.
- class selector is used to style group of multiple HTML elements.
- Writing clss selector is most preferable way of writing CSS.
- class selector uses class attribute of the HTML element
- The class name selector begins with a dot, followed by the class name itself.
Sample Live Example
<html> <head> <style type="text/css"> .heading { text-align:center; color:red; } </style> </head> <body> <h1class="heading">This is H1 Type Heading !!</h1> <h2class="heading">This is H2 Type Heading !!</h2> <h3class="heading">This is H3 Type Heading !!</h3> <h4class="heading">This is H4 Type Heading !!</h4> <h5class="heading">This is H5 Type Heading !!</h5> </body> </html>
Output :
Explanation of the Code :
We have defined following rule with class selector
.heading { text-align:center; color:red; }
- We can apply this style rule to the element with the class=”heading”.
- Any no of HTML element can have same class.
Some Rules of Using Class Selector Name :
- The class name should be comprised of letters, numbers, and hyphens only.
- Class names must start with a letter and cannot include spaces.
How to Limit a class selector to a type of element :
We can use the following selector to any HTML element by specifying the class selector.
.para1 { margin: 10px 0; padding: 20px; border: 1px solid #FFF; background-position: 20px 20px; }
But suppose we have to use this class selector only to the element of type “div”. Then we can write it as -
div.para1 { margin: 10px 0; padding: 20px; border: 1px solid #FFF; background-position: 20px 20px; }
This representation contain two selectors i.e Type Selector and Class Selector.