How to add CSS to a Webpage
When it comes to adding CSS to your document, you have a choice of methods. However, one method stands out as the most common.
There are 4 ways of adding CSS to a webpage: declare inline, embed into the head of your document, link to an external CSS file, import a CSS file.
With inline styles, style sheet information is applied directly to the HTML element. Instead of defining the style once, then applying the style against all instances of an element (say the
<p>tag), you add the style directly to the specific element you want the style to apply to.
While inline styles can be a quick and convenient way to add styles to an HTML document, this method should be used sparingly.
Adding inline styles all over a website can make it much more difficult to maintain. A small change can become a major undertaking if the style has been applied to many pages across the site.
You add all CSS information to one part of the document (usually the top). This allows you to style any element on the page from a single place. You do this by embedding the CSS information within
<style>tags in the head of your document.
For example, place the following code between the
<head>tags of your HTML document:
Here's an example of where that code fits in to an HTML document:
External style sheets are the most common method of applying styles to a website. Most modern websites use an external stylesheet to apply site-wide styles to the whole website.
External styles refer to creating a separate file that contains all style information. This file is then linked to from as many HTML pages as you like. This will often be the whole website.
To add an external stylesheet to a web page, use the
<link>tag, providing the URL of the style sheet in the
hrefattribute, as well as
For the following example, I've taken the styles from the above (embedded) example, moved them to an external style sheet, then linked to that file.
So, you can see that the HTML file no longer contains any actual CSS code. The CSS code is located in the external file.
You can also use the CSS
@importrule to import an external style sheet.
To do this, use the
You can use either of the following syntaxes:
Here, we use the same style sheet as in the previous example, but this time we use the
@importrule to import the style sheet.
Note that this method can affect performance and it's often more efficient to use the first method (i.e. with the
@importrule can also be used from within the external style sheet itself (in order to import another style sheet into that one) without incuring the same performance issues.
You're not limited to just one method of applying styles to a document. You can combine all three methods if required.
Most modern websites use external styles for most (if not all) of their styles.
However, there are many valid reasons why they might also need to use one or both of the other methods.