askvity

What is external CSS in HTML?

Published in CSS Styling 3 mins read

External CSS in HTML is a method of styling multiple HTML pages using a single, separate CSS file. This approach promotes consistency, maintainability, and efficiency in web development.

Key Aspects of External CSS:

  • Centralized Styling: External CSS allows you to define all the styling rules for your website in one or more .css files. Changes made to the CSS file are automatically reflected across all linked HTML pages.

  • File Extension: External CSS files are saved with the .css extension (e.g., styles.css).

  • Linking to HTML: HTML pages link to the external CSS file using the <link> tag within the <head> section of the HTML document.

    <!DOCTYPE html>
    <html>
    <head>
        <title>My Webpage</title>
        <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
        <h1>Welcome!</h1>
        <p>This is a paragraph styled with external CSS.</p>
    </body>
    </html>
  • Improved Maintainability: Updating the website's style becomes easier because you only need to modify the CSS file, not each individual HTML page.

  • Better Organization: Separating CSS from HTML improves code readability and makes it easier to manage the project.

  • Caching Benefits: Browsers can cache external CSS files, reducing page load times for subsequent pages viewed on the website. This significantly improves website performance.

  • Consistency: Ensures a uniform look and feel across the entire website.

Advantages of Using External CSS:

  • Consistency: Consistent styling across multiple pages.
  • Maintainability: Easier to update and maintain the website's styling.
  • Organization: Separation of concerns (structure vs. presentation).
  • Performance: Browser caching of CSS files.

Example:

Let's say you have two HTML files: index.html and about.html.

styles.css:

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    color: #333;
}

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

p {
    font-size: 16px;
    line-height: 1.5;
}

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <h1>Welcome to the Home Page!</h1>
    <p>This is the home page content.</p>
</body>
</html>

about.html:

<!DOCTYPE html>
<html>
<head>
    <title>About</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <h1>About Us</h1>
    <p>Learn more about our company.</p>
</body>
</html>

Both index.html and about.html will share the same styles defined in styles.css. Changing the styles.css file will automatically update the appearance of both pages.

In summary, external CSS is a powerful and efficient way to style HTML documents by keeping styling rules separate from the content, leading to more maintainable, organized, and performant websites.

Related Articles