There are 3 ways to add CSS to a web page:
- Inline CSS
- Internal CSS
- External CSS
Inline CSS
An inline style may be used to apply a unique style for a single element. This style must be written between the quotes in style=”…”
So here is an example of an inline style:
<!DOCTYPE html>
<html>
<body>
<h1 style=”color:blue;text-align:center;”>This is a centered heading</h1>
<p style=”color:red;”>This is a red paragraph.</p>
</body>
</html>
Internal CSS
An internal styles may be used if you want the webpage to have unique styles. Say you want to style a page for the holidays.
The internal style is defined inside the <style>…</style> element, inside the <head>…</head> section.
So here is an example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: green;
text-align:center;
}
</style>
</head>
<body>
<h1>This is a centered heading</h1>
<p>This is a regular paragraph.</p>
</body>
</html>
External CSS
With an external style sheet, you can change the look of an entire website by changing just one file! So much time saved!
You have to link this Style Sheet to every page that you want to use it inside a <link> element, inside the <head>…</head> section.
An external stylesheet can be written in any text editor and must be saved with an .css extention.
So here is an example of a style sheet that is located in a directory named “assets”:
<!DOCTYPE html>
<html>
<head><link rel=”stylesheet” href=”assets/styles.css”>
</head>
<body>
<h1>This is a centered heading</h1>
<p>This is a regular paragraph.</p>
</body>
</html>
Putting It Together (Why we call it Cascading Style Sheets)
What if there is more than one style specified for an HTML element?
When a web page is shown to a visitor, all the styles in a page will “cascade” into a new “virtual” style sheet by the following rules:
- Inline Style (inside an HTML element)
- External Style Sheet and Internal Style Sheets (in the head section & Seperate file)
- Browser default style
Also the first declaration will overwrite the subsequesnt declorations. So, an inline style has the highest priority, and will override external and internal styles and browser defaults.
TIP
There is a trick tough to get around that:
- Add !important right after the declaration but before the semicolon (;)
- Also to overwrite the inline CSS, you can add a body selector before your actual selector.
So it would look like this:
p.myselector {color:red !important;}
or
body p.myselector {color:red;}
Test It Yourself
See the Pen CSS ADDING by Ollie (@webocafe)on CodePen.