Class Selector in CSS

  1. W3C defines Class as “Specific Group of Elements“.
  2. class selector is used to style group of multiple HTML elements.
  3. Writing clss selector is most preferable way of writing CSS.
  4. class selector uses class attribute of the HTML element
  5. 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 :

  1. The class name should be comprised of letters, numbers, and hyphens only.
  2. 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.