Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to use style attribute to define style rules?
The style attribute allows you to apply CSS rules directly to individual HTML elements. This is called inline CSS and provides element-specific styling with the highest specificity.
Syntax
<element style="property1: value1; property2: value2;">
Content
</element>
Example: Basic Inline Styling
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS Example</title>
</head>
<body>
<p style="color: #36C; font-size: 18px;">This is inline CSS</p>
<div style="background-color: #f0f0f0; padding: 10px; border: 1px solid #ccc;">
Styled div with multiple properties
</div>
</body>
</html>
Example: Multiple Style Properties
<!DOCTYPE html>
<html>
<head>
<title>Multiple Inline Styles</title>
</head>
<body>
<h1 style="color: red; text-align: center; font-family: Arial, sans-serif;">
Styled Heading
</h1>
<p style="background-color: yellow; padding: 15px; margin: 20px; border-radius: 5px;">
This paragraph has background, padding, margin, and rounded corners.
</p>
<button style="background-color: #4CAF50; color: white; padding: 10px 20px; border: none; cursor: pointer;">
Styled Button
</button>
</body>
</html>
Key Points
- Highest Specificity: Inline styles override external and internal CSS
- Semicolon Separation: Multiple properties must be separated by semicolons
- No Selectors: Applies only to the specific element
- Maintenance: Harder to maintain compared to external stylesheets
When to Use Inline CSS
- Quick testing and debugging
- Element-specific overrides
- Dynamic styling with JavaScript
- Email templates (better compatibility)
Conclusion
The style attribute provides direct element styling with highest CSS specificity. While useful for specific cases, prefer external stylesheets for better maintainability in larger projects.
Advertisements
