0
0
CssHow-ToBeginner · 3 min read

How to Link a CSS File to HTML: Simple Guide

To link a CSS file to an HTML document, use the <link> tag inside the <head> section. Set rel="stylesheet" and href="your-style.css" to point to your CSS file.
📐

Syntax

The <link> tag connects your HTML to a CSS file. It must be placed inside the <head> section. The rel attribute tells the browser this is a stylesheet, and href gives the path to your CSS file.

html
<link rel="stylesheet" href="styles.css">
💻

Example

This example shows a simple HTML page linking to 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>Hello, world!</h1>
  <p>This page uses an external CSS file.</p>
</body>
</html>
Output
A webpage with a blue background, white heading text, and italic paragraph text.
⚠️

Common Pitfalls

  • Forgetting to place the <link> tag inside the <head> section can cause styles not to load.
  • Incorrect file path in href will break the link; always check the file location.
  • Missing rel="stylesheet" attribute means the browser won't treat the file as CSS.
html
<!-- Wrong way: missing rel attribute -->
<link href="styles.css">

<!-- Right way -->
<link rel="stylesheet" href="styles.css">
📊

Quick Reference

Remember these tips when linking CSS files:

  • Use <link rel="stylesheet" href="file.css"> inside <head>.
  • Check your file path carefully.
  • Use relative paths for local files and absolute URLs for online files.
  • Ensure your CSS file is saved with a .css extension.

Key Takeaways

Always place the tag inside the section of your HTML.
Use rel="stylesheet" to tell the browser the linked file is CSS.
Make sure the href attribute correctly points to your CSS file location.
Check your CSS file has the .css extension and is saved properly.
Use relative or absolute paths depending on where your CSS file is stored.