Adding CSS to Your Projects
Learn about the different ways to add CSS to HTML files.
We'll cover the following
Adding CSS to your projects
There are three ways to load CSS into a web page:
- Using a
link
tag - Using
style
tags - Using
inline
styles
Let’s take a closer look at each method:
Using a link
tag
One of the most effective ways to use CSS is to use a link
tag. This is because our CSS file is connected to all our web pages, so when we make changes to the CSS file, they’re reflected on all of the website’s pages.
We add a link
tag with the href
attribute pointing to the CSS file we want to include.
This line of code should be added inside the
head
tag of the site (and not inside thebody
tag) as follows:
<link rel="stylesheet" type="text/css" href="styles.css">
Also, the rel
and type
attributes are required because they tell the browser which kind of file we’re linking. An explanation of these attributes is given below:
- The
rel
attribute identifies the relation between the current document and the linked document. - The
type
attribute specifies the media type. - The
href
attribute provides the location of the document.
We’re free to link up as many CSS files as we’d like. However, for smaller websites, a single CSS file is desirable because our page will load faster when it only needs to find one style sheet file.
Using a style
tag
We can use CSS directly inside a style
tag, like so:
This way, we don’t have to create a separate CSS file.
The point of CSS is to separate our presentation from our document structure - so the style
tag is not the best practice. However, it can be an excellent way to test some CSS before working with a separate file quickly.
Using inline style
Another way to add CSS to a web page is to use inline style. We can add a style
attribute to an HTML tag and put our CSS in double quotes:
<div style="">...</div>
Example
Let’s alter the background-color
of the <div>
element to orange using the inline style technique
Example 2
Let’s set the font-size to
32 32px
on our <h1>
tag and change the background and font colors.
Note: The unit px stands for pixels , we’ll review at CSS units in more detail later in the course.