HTML Classes and IDs

    HTML-Logo

    When creating a website, it's often necessary to style certain elements in a specific way. In HTML, we can do this by assigning classes or IDs to our elements.

    Classes

    A class is a type of attribute that can be used to identify multiple elements on a page. You can assign the same class to as many elements as you like. In CSS, you can then select these elements and apply styles to them.

    Here is an example:

    <div class="alert">This is an alert box.</div>
    
    <style>
    .alert {
      color: red;
      font-weight: bold;
    }
    </style>
    

    output:

    This is an alert box.

    IDs

    An ID is another type of attribute that can be used to identify a single element on a page. Unlike classes, an ID should be unique and only assigned to one element. In CSS, you can select this element by its ID and apply styles to it.

    Here is an example:

    <div id="uniqueElement">This is a unique element.</div>
    
    <style>
    #uniqueElement {
      color: blue;
      font-weight: bold;
    }
    </style>
    

    output:

    This is a unique element.

    Combining Classes and IDs

    You can combine classes and IDs in your HTML. The ID will override any shared styles with the class. This is due to the specificity in CSS, where IDs have higher specificity than classes.

    Here is an example:

    <div class="alert" id="uniqueElement">This is a unique alert box.</div>
    
    <style>
    .alert {
      color: red;
      font-weight: bold;
    }
    #uniqueElement {
      color: blue;
    }
    </style>
    

    output:

    This is a unique alert box.

    Class and ID Naming

    It's important to use meaningful names for your classes and IDs to make your code easier to read and maintain. Also, remember that class and ID names are case-sensitive.

    Summary

    Classes and IDs are both ways to identify elements in HTML. They can be used to apply CSS styles, and they can also be used by JavaScript for DOM manipulation.

    Remember, use classes when you want a style to be reusable, and use IDs when you want a style to be unique to an element.