HTML Styles
What are HTML Styles?
The HTML style attribute is used to add inline CSS (Cascading Style Sheets) to HTML elements. Styles define how HTML elements are displayed, including colors, fonts, sizes, spacing, and layout.
Inline Styles
The style attribute can contain any CSS property. It's written as:
Example
<p style="color: blue;">This is a blue paragraph.</p>
<h1 style="color: red; font-size: 30px;">Red Heading</h1>
Common Style Properties
Color
Example
<p style="color: blue;">Blue text</p>
<p style="color: #ff0000;">Red text using hex</p>
<p style="color: rgb(0, 255, 0);">Green text using RGB</p>
Background Color
Example
<p style="background-color: yellow;">Yellow background</p>
<h2 style="background-color: #4b3190; color: white;">Purple background, white text</h2>
Font Size
Example
<p style="font-size: 20px;">Large text</p>
<p style="font-size: 12px;">Small text</p>
Font Family
Example
<p style="font-family: Arial;">Arial font</p>
<p style="font-family: 'Times New Roman', serif;">Times New Roman font</p>
<p style="font-family: 'Courier New', monospace;">Monospace font</p>
Text Alignment
Example
<p style="text-align: left;">Left aligned</p>
<p style="text-align: center;">Center aligned</p>
<p style="text-align: right;">Right aligned</p>
Border
Example
<p style="border: 2px solid black;">Text with border</p>
<div style="border: 1px dashed red; padding: 10px;">Dashed red border</div>
Padding and Margin
Example
<p style="padding: 20px; background-color: lightblue;">Text with padding</p>
<p style="margin: 30px; background-color: lightgreen;">Text with margin</p>
Multiple Style Properties
You can combine multiple CSS properties in a single style attribute by separating them with semicolons:
Example
<p style="color: white; background-color: #4b3190; padding: 15px; text-align: center; font-size: 18px;">
Styled paragraph with multiple properties
</p>
Using Internal CSS
Instead of inline styles, you can use internal CSS in the <head> section:
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: blue;
font-size: 16px;
}
h1 {
color: red;
text-align: center;
}
</style>
</head>
<body>
<h1>Styled Heading</h1>
<p>This paragraph is styled with internal CSS.</p>
</body>
</html>
Using External CSS
You can also link to an external CSS file for better organization:
Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Styled with external CSS</h1>
<p>This uses an external stylesheet.</p>
</body>
</html>
Best Practices
- Use inline styles sparingly: They're hard to maintain and reuse
- Prefer external CSS: It keeps HTML clean and allows styles to be reused
- Use internal CSS: For single-page websites or page-specific styles
- Separate content from presentation: HTML for structure, CSS for styling