HTML Classes
HTML Class Attribute
Section titled “HTML Class Attribute”The class attribute allows you to assign one or more class names to an HTML element. This is primarily used to target elements with CSS for styling or with JavaScript for manipulation.
Styling Multiple Elements with Classes
Section titled “Styling Multiple Elements with Classes”You can apply the same CSS styles to multiple elements by giving them the same class name.
Imagine styling several information boxes consistently:
HTML Structure:
Section titled “HTML Structure:”<div class="info-box"> <h2>London</h2> <p>London is the capital city of England...</p></div>
<div class="info-box error"> <h2>System Alert</h2> <p>An error occurred during the process.</p></div>
<div class="info-box success"> <h2>Update Complete</h2> <p>Your profile has been updated successfully.</p></div>CSS Styling:
Section titled “CSS Styling:”/* Base style for all info boxes */.info-box { border: 1px solid #ccc; margin: 20px; padding: 15px; background-color: #f9f9f9; border-radius: 5px;}
/* Specific style for error boxes */.error { border-left: 5px solid red; background-color: #ffebeb;}
/* Specific style for success boxes */.success { border-left: 5px solid green; background-color: #e6ffed;}In this example:
- All
<div>elements withclass="info-box"get the base styling. - The second
<div>has two classes (info-boxanderror). It gets the base styles plus the specific error styles. - The third
<div>hasinfo-boxandsuccessclasses, receiving base styles and success styles. - Multiple class names are separated by spaces within the
classattribute.
Using Classes on Inline Elements
Section titled “Using Classes on Inline Elements”The class attribute works just as well on inline elements like <span>, <a>, **, etc., allowing you to style specific parts of text.
Example: Highlighting text within a paragraph.
<h1>Product Announcement</h1><p>Please read the <span class="highlight-important">critical update notes</span> before proceeding.</p><p>Standard terms and conditions apply.</p>.highlight-important { background-color: yellow; color: #333; font-weight: bold;}Difference Between class and id
Section titled “Difference Between class and id”class: Can be used on multiple elements. An element can have multiple classes (space-separated). Primarily used for CSS styling and grouping elements for JavaScript.id: Must be unique within the entire HTML document. An element can only have one ID. Used for uniquely identifying an element, often for JavaScript manipulation or linking via fragment identifiers (#element-id).
Best Practice: Use classes for reusable styles and grouping. Use IDs for unique identifiers when necessary.