🎨 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:

HTML
<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:

CSS

<!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:

CSS

body {
  background-color: beige;
}

h1 {
  color: green;
  text-align: center;
}

πŸ“˜ Step 2 – Link it to HTML:

CSS

<!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