CSS in HTML
Introduction
How can we add CSS to an HTML page? We have 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
We can learn how CSS works when we write our HTML, by using the style
attribute within each HTML tag:
<h1 style="font-size: 128px">Here is a heading with a large font!</h1>
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:
<style>
tag
We can also use the uncommon <style>
tag, where we can group many selectors together:
<html>
<body>
<style>
h1 { font-size: 128px}
</style>
<h1>Here is a heading with a large font!</h1>
</body>
</html>
However, with more selectors, this can easily become messy and lengthy. Developers tend to use the next method most commonly!
External 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):
/* style.css */
h1 {
font-size: 128px
}
Then, in the HTML file, we reference the aforementioned style.css:
<!-- index.html -->
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Here is a heading with a large font!</h1>
</body>
</html>
A couple of things to note:
- The most common way to reference a .css file is through the
<link>
tag, which itself 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 thelink
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
So, in each of the above three ways, the h1
shows "Here is a heading with a large font!" in 128px size. However, the long-run maintainability of the CSS code differs considerably. We find that the last, 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!