05. style Attribute
Introduction
Section titled “Introduction”The style attribute allows you to apply CSS styles directly to HTML elements. While convenient, inline styles should be used sparingly as they reduce maintainability and reusability. Understanding when and how to use the style attribute helps balance convenience with best practices.
Basic Usage
Section titled “Basic Usage”<p style="color: red; font-size: 18px;">Red text</p>Multiple Properties
Section titled “Multiple Properties”<div style="background-color: blue; color: white; padding: 20px;"> Styled content</div>Common Use Cases
Section titled “Common Use Cases”Dynamic Styling
Section titled “Dynamic Styling”<div style="display: none;" id="hidden">Hidden content</div>Quick Testing
Section titled “Quick Testing”<div style="border: 1px solid red;">Testing</div>Email HTML
Section titled “Email HTML”<p style="color: #333; font-family: Arial;">Email content</p>Limitations
Section titled “Limitations”No Reusability
Section titled “No Reusability”<!-- Styles can't be reused --><p style="color: blue;">Text 1</p><p style="color: blue;">Text 2</p>Hard to Maintain
Section titled “Hard to Maintain”<!-- Difficult to update multiple instances --><p style="color: blue;">Text</p>Best Practices
Section titled “Best Practices”Use Sparingly
Section titled “Use Sparingly”<!-- Good: For dynamic or one-off styles --><div style="display: none;">Hidden</div>
<!-- Avoid: For repeated styles --><p style="color: blue;">Text</p><p style="color: blue;">More text</p>Prefer External CSS
Section titled “Prefer External CSS”<!-- Good: External CSS --><link rel="stylesheet" href="styles.css">
<!-- Avoid: Inline for everything --><div style="...">Content</div>