In HTML and CSS, classes and IDs are attributes used to apply styles or behaviors to specific elements on a webpage.
-
Class:
- A class is an attribute that can be applied to one or more HTML elements to define a group or category that shares common styling or functionality.
-
Classes are defined using the
class
attribute in HTML elements and are styled using CSS rules. - Multiple elements can have the same class, allowing you to apply the same styling or behavior to multiple elements without duplicating code.
- Example:
<p class="highlight">This is a paragraph with a highlight class.</p>
In CSS:
.highlight { background-color: yellow; }
-
ID:
- An ID is similar to a class but is intended to uniquely identify a single element on a webpage.
-
IDs are defined using the
id
attribute in HTML elements and are styled using CSS rules. - Unlike classes, each element should have a unique ID within a webpage. Using the same ID for multiple elements is invalid HTML and can lead to unexpected behavior.
- IDs are often used to target specific elements for styling or JavaScript interactions.
- Example:
<div id="header">This is the header.</div>
In CSS:
#header { font-size: 24px; font-weight: bold; }
classes and IDs are both attributes used to apply styling or behaviors to HTML elements, but classes are typically used for grouping multiple elements, while IDs are used to uniquely identify individual elements. Additionally, IDs should be unique within a webpage, while classes can be applied to multiple elements.