Linking CSS to HTML
Learn the differences between <link>, <style> and inline styles.
Three methods
There are three ways to attach CSS to an HTML page. The external method links a separate .css file with <link>. The internal method writes a <style> tag inside the HTML. The inline method puts styles directly on a tag's style attribute.
The most common is the external method; one file styles many pages.
External stylesheet
In the external method, CSS lives in a separate styles.css file. You put a <link> tag inside the HTML <head>: <link rel='stylesheet' href='styles.css'>.
The benefit is large. The browser caches the CSS once, and every page loads fast. To try a new theme, you change a single file and the change ripples across the whole site at once.
Style tag and inline
In the internal method you put a <style> tag inside the HTML <head>; the CSS declarations live inside the HTML file. It is handy for styles that apply to a single page; other pages do not see them.
The inline method writes declarations on a style attribute: <p style='color: navy'>. It works for a quick fix but is best avoided in daily use, since even a single element needs a file change.
Exercise Add a body block for the external file
Add a body block that would go inside an external stylesheet. It must contain a font-family: sans-serif declaration.
Show example solution
/* add the body block */
body {
font-family: sans-serif;
}
Test yourself
-
What does rel='stylesheet' in the link tag indicate?
<link rel="stylesheet" href="styles.css">- That this link points to a stylesheet
- The page title bar text
- The HTML document character encoding
- The page language (e.g. English)
Show answer
That this link points to a stylesheet — Correct. rel='stylesheet' says this link points to a stylesheet.
-
Open the heading block in the external file
/* styles.css — external file */ ____ { color: darkblue; }Show answer
/* styles.css — external file */ h1 { color: darkblue; } -
Match each method to where it lives
- External CSS
- linked via a link tag
- Style tag
- lives in the head section
- Inline style
- on the tag's style attribute