Add CSS to HTML

Three Ways to Insert CSS

There are three ways of inserting a style sheet:

  • External style sheet
  • Internal style sheet
  • Inline style

External Style Sheet

An external style sheet is for reusing the style across many web pages.

With an external style sheet, you can change the style for many pages by changing one file.

We add external style sheet to a page using the <link> tag. The <link> tag goes inside the head section:


<!DOCTYPE HTML> //from   w w w.  j a  v  a 2 s. com
<html> 
    <head> 
        <head>
        <link rel="stylesheet" type="text/css" href="mystyle.css" />
        </head>
    </head> 
    <body> 
        <p class='center'>Visit the website</p> 
        <p class='center'>Visit the website</p> 
        <h1 class='center'>Visit the website</h1> 
    </body> 
</html>

An external style sheet can be written in a text editor and saved in a file with .css extension.

An example of a style sheet file is shown below:


hr {color:red;}
p {margin-left:20px;}
.center {text-align:center;}

Internal Style Sheet

An internal style sheet is used within a single HTML document which has a unique style.

The internal styles stays in the head section of an HTML page within the <style> tag.


<!DOCTYPE HTML> 
<html> 
    <head> 
        <style type="text/css"> 
        .center {text-align:center;}<!--from w  ww .j a  v  a  2  s . c o  m-->
        </style> 
    </head> 
    <body> 
        <p class='center'>Visit the website</p> 
    </body> 
</html>

Click to view the demo

The code above generates the following result.

Add CSS to HTML

Inline Styles

Inline styles stays with in the target tag. The inline style attribute can contain any CSS property.

The following example shows how to change the color and the left margin of a paragraph:


<p style="color:sienna;margin-left:20px">This is a paragraph.</p>

Put it to a HTML document.


<!DOCTYPE HTML> 
<html> 
    <body> 
        <p style="color:red;margin-left:20px">This is a paragraph.</p>
    </body> 
</html><!--from w w w . j a  va2s  . c om-->

Click to view the demo

The code above generates the following result.

Add CSS to HTML

Sequence of Multiple Style Sheets

If a property is set for the same selector in different style sheets, the inline style wins.

The order of Cascading order:

  1. Inline style inside an HTML element
  2. Internal style sheet in the head section
  3. External style sheet
  4. Browser default

The inline style has the highest priority. It overrides a style defined inside the <head> tag, or in an external style sheet, or a browser default value.

If the link to the external style sheet is under the internal <style> tag in HTML <head>, the external style sheet will override the internal style sheet.