What are Classes and Ids in HTML & CSS?
Classes
To target specific elements, classes and ids are necessary.
Classes allows CSS to select and access specific elements.
An example of a class in HTML would be: <h1 class="intro>This is my Life</h1>
An example in CSS would be:
.intro {
color: red;
font-weight: bold;
}
Click here to view an example of classes.
IDs
An ID defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).
An example of an ID in HTML would be: <p id="story">My story begins with...</p>
An example in CSS would be:
#story {
color:blue;
font-size:12px;
}
Click here to view an example of ids.
The benefit of this is that you can have the same HTML element, but present it differently depending on its class or ID.
The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.
In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”).