CSS in HTML
We can add CSS in HTML with at least three ways:
- In-line (
style
attribute with an HTML tag) <style>
tag (anywhere on an HTML page)- External style sheets (on a separate file but referenced by the HTML page)
In-line styles
When we write our HTML, we can learn how CSS works by using the style
attribute within each HTML tag:
1<h1 style="font-size: 128px">Here is a heading with a large font!</h1>
2
During development, we can use these in-line styles for testing out a specific styling. However, we would usually refine it later by using external style sheets or, if really necessary, with the <style>
tag:
The <style>
tag
We can also use the uncommon <style>
tag, where we can group many selectors together:
1<html>
2 <body>
3 <style>
4 h1 { font-size: 128px}
5 </style>
6 <h1>Here is a heading with a large font!</h1>
7 </body>
8</html>
However, with more selectors, this can easily become messy and lengthy. Developers tend to use the next method most commonly!
External style sheets
Let's first look at what "CSS" actually means:
Cascading
The "C" in CSS refers to "cascading". That means any later rule becomes the new rule:
1h1 {
2 color: green;
3}
4
5.red {
6 /* any element with class="red" */
7 color: red;
8}
Style sheets
The "SS" (style sheets) in "CSS" allows us to separate the styling corners from the HTML file, by placing them into a separate file called a style sheet (typically with the extension .css):
1/* style.css */
2
3h1 {
4 font-size: 128px
5}
Then, in the HTML file, we reference the aforementioned style.css:
1<!-- index.html -->
2<html>
3
4 <head>
5 <link rel="stylesheet" href="style.css">
6 </head>
7
8 <body>
9 <h1>Here is a heading with a large font!</h1>
10 </body>
11
12</html>
A couple of things to note:
- The most common way to reference a .css file is through the
<link>
tag, which itself usually resides in the<head>
tag - The style.css file can reside in any folder but we must reference it properly
- if index.html is the root folder and style.css is in a folder such as /styles/main/ then the
link
tag should have anhref
of /styles/main/style.css
- if index.html is the root folder and style.css is in a folder such as /styles/main/ then the
So, in each of the above three ways, the h1
shows "Here is a heading with a large font!" in 128px size.
Separation of concerns
However, the long-run maintainability of the CSS code differs considerably. We find that the last (the external style sheet) method, works best!
Using an external style sheet not only allows for a separation-of-concerns (HTML and CSS live in different files) but also allows for code reusability. We could use the CSS in other HTML files! We would simply re-use the line with the <link>
tag in, say, about.html, and the CSS in style.css would work in about.html!