CSS Tutorial menu

How to Add CSS

There are three ways to add CSS to an HTML page: inline, internal and external.

1. Inline CSS

Inline CSS goes inside the style attribute of one element. It styles only that element.

Example

html
<!DOCTYPE html>
<html>
<body>

<h1 style="color: teal; text-align: center;">Welcome</h1>
<p style="color: gray;">This paragraph uses inline CSS.</p>
<p>This paragraph has no style.</p>

</body>
</html>
Try it Yourself »

Inline CSS is quick for a small test, but it mixes style with content. If you have 50 headings, you must write the style 50 times.

2. Internal CSS

Internal CSS goes inside a <style> element in the <head> of the page. It styles the whole page.

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color: #eef2ff;
}
h1 {
  color: #264de4;
}
p {
  font-size: 18px;
}
</style>
</head>
<body>

<h1>Karachi Weather</h1>
<p>Today is sunny with a sea breeze in the evening.</p>
<p>Tomorrow will be hot and humid.</p>

</body>
</html>
Try it Yourself »

Internal CSS is good for a single page, and it is what we use in most examples in this tutorial, so the Try it editor can run them.

3. External CSS

External CSS is written in a separate file that ends with .css. Each HTML page links to it with a <link> element in the <head>.

The HTML file, index.html:

Example

html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<h1>Ali's Computer Repair</h1>
<p>Laptops, printers and phones repaired in one day.</p>

</body>
</html>

The CSS file, styles.css:

Example

css
body {
  font-family: Arial, sans-serif;
  background-color: #fafafa;
}

h1 {
  color: darkblue;
}

The CSS file has no <style> tags, only CSS rules.

Real websites use external CSS. One file styles every page, the browser saves (caches) it after the first visit, and your HTML stays clean.

Comparing the Three Ways

WayWhere it goesStylesBest for
Inlinestyle attributeOne elementQuick tests, one-off changes
Internal<style> in <head>One pageSingle-page demos
ExternalA separate .css fileMany pagesReal websites

Which One Wins?

If the same element gets styles from several places, the browser uses this order. Later items win over earlier ones when the selectors are equally specific:

  1. The browser's default styles
  2. External and internal style sheets (in the order they appear in the page)
  3. Inline styles

So an inline style beats a rule in a style sheet.

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
p {
  color: blue;
}
</style>
</head>
<body>

<p>I am blue from the internal style sheet.</p>
<p style="color: red;">I am red because inline CSS wins.</p>

</body>
</html>
Try it Yourself »

Exercise

Exercise

Which HTML element connects an external CSS file to a page?

Learn CSS with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp