CSS Classes and ID
CSS (Cascading Style Sheets) classes and IDs are essential for styling HTML elements. They allow you to apply consistent styles across multiple elements or target specific elements with unique styles.
CSS Classes
Definition
- Classes are reusable styles that can be applied to multiple HTML elements. They are defined with a . (dot) prefix in the CSS and can be assigned to an HTML element using the class attribute.
Usage
- Creating a Class in CSS
.classname { property: value;}- Applying a Class in HTML
<div class="classname">Content</div>Example
- CSS:
.highlight { background-color: yellow; color: black;}- HTML:
<p class="highlight">This paragraph is highlighted.</p><p class="highlight">This paragraph is also highlighted.</p>Characteristics
- Reusability: Classes can be applied to multiple elements.
- Flexibility: Multiple classes can be assigned to a single element.
<div class="class1 class2">Content</div>CSS IDs
Definition
- IDs are unique styles that are applied to a single HTML element. They are defined with a # (hash) prefix in the CSS and can be assigned to an HTML element using the id attribute.
Usage
- Creating an ID in CSS:
#idname { property: value;}- Applying an ID in HTML
<div id="idname">Content</div>Example
- CSS:
#unique { background-color: blue; color: white;}- HTML:
<p id="unique">This paragraph has a unique style.</p>Characteristics
- Uniqueness: IDs should be unique within a document, meaning they should only be applied to one element.
- Specificity: IDs have higher specificity than classes, making them useful for overriding styles.
Differences Between Classes and IDs
-
Scope:
- Classes can be reused on multiple elements.
- IDs should be unique to a single element.
-
Specificity:
- IDs have a higher specificity than classes, so they take precedence when both are applied to an element.