Ways to Add CSS

There are three primary ways to add CSS to an HTML document: [1, 2]

  • Inline CSS:
    • This method involves applying CSS styles directly to individual HTML elements using the style attribute within the element's opening tag.
    • Example:
        <p style="color: blue; font-size: 16px;">This is a blue paragraph.</p>


 

  • Use Case: Suitable for applying unique styles to a single element or for quick, small adjustments.
  • Internal CSS (Embedded CSS):
    • This method involves placing CSS rules within a &lt;style&gt; tag inside the &lt;head&gt; section of your HTML document.
    • Example:
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                h1 {
                    color: green;
                    font-family: Arial, sans-serif;
                }
                p {
                    color: black;
                }
            </style>
        </head>
        <body>
            <h1>This is a heading.</h1>
            <p>This is a paragraph.</p>
        </body>
        </html>


 

  • Use Case: Ideal for styling a single HTML page when the styles are specific to that page and not intended for reuse across multiple pages.
  • External CSS:
    • This is the most common and recommended method for larger projects. It involves creating a separate .css file (e.g., styles.css) containing all your CSS rules, and then linking this file to your HTML document using the &lt;link&gt; tag within the &lt;head&gt; section. [3]
    • Example (HTML file - index.html):
        <!DOCTYPE html>
        <html>
        <head>
            <link rel="stylesheet" href="styles.css">
        </head>
        <body>
            <h1>Hello World!</h1>
        </body>
        </html>


 

Example (CSS file - styles.css).


 

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


 

  • Use Case: Best for maintaining consistency and reusability of styles across an entire website, as changes in the external CSS file will affect all linked HTML pages.

Precedence: When multiple styling methods are used for the same element, inline styles have the highest precedence, followed by internal styles, and then external styles.