Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

css
class
id
selectors

Class and ID selectors in CSS

Educative Answers Team

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. 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.


RELATED TAGS

css
class
id
selectors
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring