CSS Inclusion

How To Add CSS

There are three ways to insert CSS in HTML documents.

  1. Inline CSS
  2. Internal CSS
  3. External CSS

1) Inline CSS:

Inline CSS is used to apply style on a single line or element.

Example:

file name- index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Inline CSS</title>
  </head>
  
  <body>
    <h1 style="color:red;text-align:center;">This is a heading</h1>
    <p style="color:blue;">This is a paragraph.</p>
  </body>
</html>

This will produce the following result −

2) Internal CSS:

Internal CSS is used to apply CSS on a single document or page.

It is written inside the <style> tag within head section of html. Rules defined using this syntax will be applied to all the elements available in the document.

Example:

file name- index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Internal CSS</title>
    <style>
      body {
          background-color: linen;
           }
      h1 {
         color: maroon;
         margin-left: 40px;
        }
      p {
         font-family: 'Courier New', Courier, monospace;
         font-size: 18px;
        }
  </style>
 </head>
  
  <body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
  </body>
</html>

This will produce the following result −

3) External CSS:

External CSS is used to apply CSS on multiple pages or all pages.

We write all the CSS code in a separate CSS file. Its extension must be .css for example style.css

This CSS file should be linked to html pages using <link> tag in <head> section.

Example:

file name- index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Internal CSS</title>
    <link rel="stylesheet" href="./style.css">
 </head>
  
  <body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
  </body>
</html>

file name- style.css

body {
    background-color: rgba(150, 223, 186, 0.726);
  }
  
h1 {
    color: rgb(202, 0, 0);
    border: 2px solid blue;
    display: inline-block;
    margin-top: 20px;
    padding: 6px;
   }

p {
   margin-left: 20px;
   font-weight: bold;
  }

This will produce the following result −