Use CSS in HTML Files
There are three ways of using CSS in HTML files1.
(1) External CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: blue;
}
p {
text-align: center;
color: green;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>Paragraph</p>
</body>
</html>
where style.css
and html0.html
are in the same directory. The <link>
tag is used to2:
The <link>
tag defines the relationship between the current document and an external resource.
The <link>
tag is most often used to link to external style sheets or to add a favicon to your website.
The <link>
element is an empty element, it contains attributes only.
where rel
property “(required) specifies the relationship between the current document and the linked document”, and href
property “specifies the location of the linked document”.
(2) Internal CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: blue;
}
p {
text-align: center;
color: green;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>Paragraph</p>
</body>
</html>
where <style>
tag3:
The <style>
tag is used to define style information (CSS) for a document.
Inside the <style>
element you specify how HTML elements should render in a browser.
The <style>
element must be included inside the <head>
section of the document.
(3) Inline CSS
1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
<body>
<h1 style="text-align:center;color:red;">Heading 1</h1>
<h2 style="text-align:center;color:blue;">Heading 2</h2>
<p style="text-align:center;color:green;">Paragraph</p>
</body>
</html>
As for the cascading order when there is more than one style definition for the same HTML tag1:
All the styles in a page will “cascade” into a new “virtual” style sheet by the following rules, where number one has the highest priority:
- Inline style (inside an HTML element)
- External and internal style sheets (in the head section)
- Browser default
So, an inline style has the highest priority, and will override external and internal styles and browser defaults.
Reference