How to Add Css

Itacen Sabacok | May 6, 2021

3 Ways to Insert CSS

  1. External (with style sheet file)
  2. Internal (with <style> element)
  3. Inline (with style attribute)

1. External CSS

HTML page must include a reference to the external style sheet file inside the <link> element in the head section.

 1<!DOCTYPE html>
 2<html>
 3<head>
 4<link rel="stylesheet" href="external_file.css">
 5</head>
 6<body>
 7
 8<div>
 9  <p>Hello World</p>
10</div>
11
12</body>
13</html>

here is the sample of external_file.css file.

 1body {
 2  width: 100%;
 3  height: 100px;
 4  background-color: blue;
 5}
 6
 7p {
 8  text-align: center;
 9  font-size: 2em;
10}

2. Internal CSS

Styles can be directly defined within the <style> element in head section.

 1<!DOCTYPE html>
 2<html>
 3<head>
 4<style>
 5  body {
 6    width: 100%;
 7    height: 100px;
 8    background-color: blue;
 9  }
10
11  p {
12    text-align: center;
13    font-size: 2em;
14  }
15</style>
16</head>
17<body>
18
19<div>
20  <p>Hello World</p>
21</div>
22
23</body>
24</html>

3. Inline CSS

Styles can be directly defined within the relevant element with style attribute.

 1<!DOCTYPE html>
 2<html>
 3<head>
 4<title>How to Add Css</title>
 5</head>
 6<body>
 7
 8<div>
 9  <p style="text-align: center;font-size: 2em;">Hello World</p>
10</div>
11
12</body>
13</html>

NOTE

These 3 ways can be used at the same time then know the ordering is like below from highest priority to lowest priority

  1. Inline style (inside an HTML element)
  2. External and internal style sheets (in the head section)
  3. Browser default