Class and ID selectors in CSS

In CSS, class and ID selectors are used to identify various HTML elements. The main benefit of setting class or ID is that you can present the same HTML element differently, depending on its class or ID.

Class selector

The class selector selects elements with a specific class attribute. It matches all the HTML elements based on the contents of their class attribute. The . symbol, along with the class name, is used to select the desired class.

Syntax

.class-name {
/* Define properties here */
}

ID selector

The ID selector matches an element based on the value of its id attribute. In order for the element to be selected, its ID attribute must exactly match the value given in the selector. The # symbol and the id of the HTML element name are used to select the desired element.

Syntax

#idname {
/* Define properties here */
}

The difference between Class and ID selector

The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element.

svg viewer

Code

The following code demonstrates the difference between class and ID selectors, ​and how to set their individual properties. The code sets a class for the div and, therefore, all the elements within the div will have this class.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Selectors Example</title>
    <link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
    <!-- HTML content -->
    <div class="main">
        <h3>Welcome to Educative!</h3>
        <p >Sample paragraph with an ID</p>
        <p>Sample paragraph with no ID</p>
    </div>
</body>
</html>
Div with class selector

Code

However, one of the paragraphs is assigned an ID which allows individual properties to be set for this particular paragraph. These properties are set using the appropriate class and ID selectors.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Selectors Example</title>
    <link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
    <!-- HTML content -->
    <div class="main">
        <h3>Welcome to Educative!</h3>
        <p id = "demo">Sample paragraph with an ID</p>
        <p>Sample paragraph with no ID</p>
    </div>
</body>
</html>
Paragraph with ID with class selector

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved