04. External CSS
Introduction
Section titled “Introduction”External CSS separates styles from HTML by placing CSS rules in separate .css files. This approach promotes maintainability, reusability, and better organization. External CSS is the preferred method for styling websites with multiple pages.
Basic Usage
Section titled “Basic Usage”CSS File (styles.css)
Section titled “CSS File (styles.css)”body { font-family: Arial, sans-serif; margin: 0; padding: 20px;}
h1 { color: #333; font-size: 2em;}HTML File
Section titled “HTML File”<!DOCTYPE html><html><head> <link rel="stylesheet" href="styles.css"></head><body> <h1>Title</h1> <p>Content</p></body></html>link Element
Section titled “link Element”Basic Link
Section titled “Basic Link”<link rel="stylesheet" href="styles.css">With Media Query
Section titled “With Media Query”<link rel="stylesheet" href="styles.css" media="screen"><link rel="stylesheet" href="print.css" media="print">Multiple Stylesheets
Section titled “Multiple Stylesheets”<link rel="stylesheet" href="reset.css"><link rel="stylesheet" href="main.css"><link rel="stylesheet" href="components.css">Advantages
Section titled “Advantages”Reusability
Section titled “Reusability”Share styles across pages:
<!-- Same CSS for all pages --><link rel="stylesheet" href="styles.css">Maintainability
Section titled “Maintainability”Update styles in one place:
/* Change once, applies everywhere */h1 { color: blue; }Caching
Section titled “Caching”Browsers cache CSS files:
<!-- Cached for faster subsequent loads --><link rel="stylesheet" href="styles.css">Organization
Section titled “Organization”Better code organization:
styles/ ├── main.css ├── components.css └── utilities.cssBest Practices
Section titled “Best Practices”Use External CSS
Section titled “Use External CSS”<!-- Good: External CSS --><link rel="stylesheet" href="styles.css">
<!-- Avoid: Inline for everything --><div style="...">Content</div>Organize Files
Section titled “Organize Files”<link rel="stylesheet" href="css/reset.css"><link rel="stylesheet" href="css/main.css">