Table of Contents

    Class and ID Selectors in CSS: A Comprehensive Guide

    Class and ID Selectors

    There are variety of selectors that help us in applying styles to particular element based on our need.

    Let's start with learning about the Class and ID selectors.

    The CSS id Selector

    The id selector uses the id attribute of an HTML element to select a specific element.

    The id of an element is unique within a page, so the id selector is used to select one unique element!

    To select an element with a specific id, write a hash (#) character, followed by the id of the element.

    Note: An id name cannot start with a number!

    Example

    The CSS rule below will be applied to the HTML element with id="para1": 

    
    <style>
    #paragraph {
      text-align: center;
      color: red;
    }
    </style> 
    

    Output:

    If you will run above code, you will get below output.


    Full code:

    
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    #paragraph {
      text-align: center;
      color: red;
    }
    </style>
    </head>
    <body>
    
    <p id="paragraph">Hello World!</p>
    <p>This paragraph is not affected by the style.</p>
    
    </body>
    </html> 
    
    

    The CSS class Selector

    The class selector selects HTML elements with a specific class attribute.

    To select elements with a specific class, write a period (.) character, followed by the class name.

    Example

    In this example all HTML elements with class="center" will be red and center-aligned: 

    You can also specify that only specific HTML elements should be affected by a class.

    
    .center {
      text-align: center;
      color: red;
    }
    

    Example

    In this example only <p> elements with class="center" will be red and center-aligned: 

    HTML elements can also refer to more than one class.

    
    p.center {
      text-align: center;
      color: red;
    }
    

    Example

    In this example the <p> element will be styled according to class="center" and to class="large": 

    
    <p class="center large">This paragraph refers to two classes.</p>