How to Link CSS in HTML: Simple Guide with Examples
To link CSS in HTML, use the
<link> tag inside the <head> section with attributes rel="stylesheet" and href pointing to your CSS file. This tells the browser to load and apply the CSS styles to your HTML page.Syntax
The <link> tag connects your HTML to a CSS file. It must be placed inside the <head> section. The main parts are:
rel="stylesheet": tells the browser this link is a style sheet.href="path/to/file.css": the path to your CSS file.type="text/css"is optional and usually not needed in modern HTML.
html
<link rel="stylesheet" href="styles.css">
Example
This example shows a simple HTML page linking an external CSS file named styles.css. The CSS changes the background color and text style.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Link CSS Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Welcome to My Page</h1> <p>This text is styled by an external CSS file.</p> </body> </html>
Output
A webpage with a blue background, white heading text, and italic paragraph text.
Common Pitfalls
Common mistakes when linking CSS include:
- Placing the
<link>tag outside the<head>section, which may cause styles to load late or not at all. - Incorrect
hrefpath, like typos or wrong folder location, so the CSS file is not found. - Forgetting
rel="stylesheet", so the browser does not treat the link as CSS.
html
<!-- Wrong way: missing rel attribute --> <link href="styles.css"> <!-- Correct way --> <link rel="stylesheet" href="styles.css">
Quick Reference
| Attribute | Purpose | Example |
|---|---|---|
| rel | Defines the relationship; use "stylesheet" for CSS | rel="stylesheet" |
| href | Path to the CSS file | href="styles.css" |
| type | Specifies the MIME type (optional) | type="text/css" |
Key Takeaways
Always place the tag inside the section of your HTML.
Use rel="stylesheet" and href="your-style.css" to link CSS correctly.
Double-check the CSS file path to avoid loading errors.
Modern HTML does not require the type attribute for CSS links.
Linking CSS externally keeps HTML clean and styles reusable.