Adding CSS to HTML

Adding CSS to HTML can be done in three main ways: inline CSS, internal CSS, and external CSS. Here’s how each method works:

Inline CSS

Inline CSS is used to apply a unique style to a single HTML element. To use inline CSS, add the style attribute directly within the HTML tag and set the CSS properties and values.

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inline CSS Example</title>
</head>
<body>
    <h1 style="color: blue; text-align: center;">Hello, world!</h1>
</body>
</html>

Internal CSS

Internal CSS is used to define styles for a single HTML page. You define internal CSS within a <style> element inside the <head> section of the HTML document.

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal CSS Example</title>
    <style>
        body {
            background-color: lightblue;
        }
        h1 {
            color: navy;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>Hello, world!</h1>
</body>
</html>

External CSS

External CSS is used to define styles for multiple HTML pages. You link an external CSS file to an HTML document using the <link> element within the <head> section. This method is the most efficient way to manage and maintain styles across multiple pages.

Example: Create an external CSS file (styles.css):


body {
    background-color: lightblue;
}
h1 {
    color: navy;
    text-align: center;
}

Link the external CSS file in your HTML document:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>External CSS Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Hello, world!</h1>
</body>
</html>

Best Practices

Use external CSS: Whenever possible, use external CSS for better maintainability and separation of concerns.

Keep it organized: Group related styles together in your CSS files and use comments to describe sections.

Use meaningful names: Use descriptive class and ID names to make your CSS easier to understand and maintain.

Avoid inline CSS: Inline CSS should be avoided unless necessary for quick tests or overrides.