CSS
π¨ Ways to Add CSS to HTML
CSS (Cascading Style Sheets) can be added to an HTML page in three different ways:
- Inline CSS
- Internal CSS
- External CSS
Letβs explore each method π
π§© 1. Inline CSS
Inline CSS is applied directly inside an HTML element using the style attribute.
Example:
<h1 style="color: blue; text-align: center;">Hello World!</h1>
π Explanation:
The CSS is written directly inside the <h1> tag and affects only that specific element.
β Advantages:
- Quick and easy for small changes
- Useful for testing styles
β Disadvantages:
- Not reusable
- Makes code messy when overused
- Difficult to maintain
π‘ Best Use Case: Quick fixes or temporary styling.
π 2. Internal CSS
Internal CSS is defined inside a <style> tag within the <head> section of an HTML document.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Internal CSS Example</title>
<style>
body {
background-color: lightblue;
}
h1 {
color: darkblue;
text-align: center;
}
</style>
</head>
<body>
<h1>Hello CSS!</h1>
</body>
</html>
π Explanation:
All styles are placed in one section and apply only to that single page.
β Advantages:
- Easy to manage for small projects
- Keeps styles organized in one place
β Disadvantages:
- Not reusable across multiple pages
- Inefficient for larger websites
π‘ Best Use Case: Single-page projects or small demos.
π 3. External CSS
External CSS is written in a separate .css file and linked to the HTML document.
π Step 1 β Create style.css:
body {
background-color: beige;
}
h1 {
color: green;
text-align: center;
}
π Step 2 β Link it to HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>External CSS Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello External CSS!</h1>
</body>
</html>
π Explanation:
The <link> tag connects the external CSS file to the HTML page.
β Advantages:
- Reusable across multiple pages
- Cleaner and more maintainable code
- Faster performance with browser caching
β Disadvantages:
- Styles wonβt load if the file is missing
- Requires proper file linking
π‘ Best Use Case: Professional and large-scale projects.
βοΈ Quick Comparison
| Method | Location | Scope | Best For |
|---|---|---|---|
| Inline | Inside HTML tag | Single element | Small quick fixes |
| Internal | <style> tag |
One page | Small projects |
| External | .css> file | Entire website | Professional projects |
π‘ Summary
- Beginners often start with Internal CSS
- Real-world projects use External CSS
- Inline CSS should be avoided except for quick fixes
