How to Add CSS to an HTML page

CSS is attached to an HTML page in different ways.

Using the link tag

The link tag is the way to include a CSS file. This is the preferred way to use CSS as it's intended to be used: one CSS file is included by all the pages of your site, and changing one line on that file affects the presentation of all the pages in the site.

To use this method, you add a link tag with the href attribute pointing to the CSS file you want to include. You add it inside the head tag of the site (not inside the body tag):

<link rel="stylesheet" type="text/css" href="myfile.css">

using the style tag

Instead of using the link tag to point to separate stylesheet containing our CSS, we can add the CSS directly inside a style tag. This is the syntax:

<style>
  ...our CSS...;
</style>

Using this method we can avoid creating a separate CSS file. I find this is a good way to experiment before "formalising" CSS to a separate file, or to add a special line of CSS just to a file.

inline styles

Inline styles are the third way to add CSS to a page. We can add a style attribute to any HTML tag, and add CSS into it.


<div style="">...</div>

Example:


<div style="background-color: yellow">...</div>

Example

<!DOCTYPE HTML>
<html>
    <head>
      <style>
        P > span {
          color :yellow
          }
      </style>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <title>Title of the Document</title>
    </head>
    <body>
      <p> 
        <span>This is yellow</span>
        <strong> 
          <span>This is not yellow</span>
        </strong>
      </p>
      <p style="background-color: yellow">The background of this text will be yellow</p>
    </body>
  </html>