Using CSS in HTML Documents

Cascading Style Sheets (CSS) is used to style HTML content. In this tutorial, we will explore two primary methods for applying CSS to an HTML document: using the <style> tag for internal styles and the <link> tag for external stylesheets.

1. Using the <style> Tag

The <style> tag is used to define internal CSS within an HTML document. It is placed inside the <head> section of your HTML file.


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Styling with Internal CSS</title>
    <style>
        body {
            background-color: #f0f0f0;
            font-family: Arial, sans-serif;
        }
        h1 {
            color: blue;
            text-align: center;
        }
        p {
            color: green;
        }
    </style>
</head>
<body>
    <h1>Welcome to CSS Tutorial</h1>
    <p>This paragraph is styled using internal CSS.</p>
</body>
</html>
                    

In this example, we define styles for the body, h1, and p elements directly in the HTML document. This is useful for small projects or quick tests.

2. Using the <link> Tag

The <link> tag is used to link an external CSS stylesheet to your HTML document. This method is preferred for larger projects to keep styles organized and reusable.


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Styling with External CSS</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Welcome to CSS Tutorial</h1>
    <p>This paragraph is styled using external CSS.</p>
</body>
</html>
                    

In the example above, the link tag includes an external stylesheet named styles.css. The contents of styles.css might look like this:


body {
    background-color: #f0f0f0;
    font-family: Arial, sans-serif;
}
h1 {
    color: blue;
    text-align: center;
}
p {
    color: green;
}
                    

3. Advantages of Each Method

Here are some advantages of using each method:

  • Internal CSS (<style>):
    • Simple to implement for small documents.
    • Quickly apply styles to a specific page.
  • External CSS (<link>):
    • Promotes reusability of styles across multiple pages.
    • Keeps HTML files cleaner and easier to manage.

4. Conclusion

CSS is essential for styling HTML content effectively. Use internal CSS for small projects or testing, and external CSS for larger projects that require consistent styling across multiple pages. By understanding and utilizing these methods, you can enhance the presentation of your web content.

Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.

top-home