< Back

Using Cascading Style Sheets in HTML

2012-06-08

Introduction

Cascading Style Sheets (CSS) allow customized styles to be applied to an HTML document. Instead of relying on the browser’s default font, size and color for a heading or a paragraph, CSS allows you to define custom styles for your page’s text, as well as many other page elements.

This article will show the three methods for using CSS in your HTML pages.

1. Inline CSS

Inline CSS allows styles to be applied individually to a particular HTML element. For example, if you have a plain text paragraph:

<p>This is a paragraph</p>

You can use the style attribute to apply custom formatting to the paragraph, such as color the text red:

<p style="color: #ff0000;">This is a paragraph</p>

This works fine for applying CSS formatting to individual elements, but it would get very tedious if you had to apply styles to every individual element in each document using this method:

<p style="
	font-family: arial, helvetica, sans-serif;
	color: #100515; 
	margin: 0.5em 0 1em 0;
">This is a paragraph</p>

<p style="
	font-family: arial, helvetica, sans-serif;
	color: #100515; 
	margin: 0.5em 0 1em 0;
">This is a second paragraph</p>

So, it would be useful to apply page-wide styles…

2. Page Specific Style Sheet

Styles that are specific to a particular page can be placed within a <style> element in the <head> section of your HTML page:

<head>
	<title>Example Page</title>
	<style type="text/css">
	p {
		font-family: arial, helvetica, sans-serif;
		color: #100515; 
		margin: 0.5em 0 1em 0;
	}
	</style>
</head>

This particular example would make all paragraph elements (<p>) formatted with custom font, color and margin settings.

Modern HTML standards (HTML 4.01, XHTML 1.0, HTML5, etc) state that style sheets MUST be within the <head> section. In practice, however, browsers will still use the stylesheet correctly if you place it elsewhere in your document and not in the <head> section.

3. External Style Sheet

External style sheets are the best way to simply apply CSS formatting to many pages, such as applying a common set of styles to an entire site.

First, you place all your global styles in a single CSS file, and give it a name such as style.css:

h1 {
	font-family: times, serif;
	color: #001285; 
	margin: 2em 0 1em 0;
}

p {
	font-family: arial, helvetica, sans-serif;
	color: #100515; 
	margin: 0.5em 0 1em 0;
}

Now, you need to tell every HTML page to use this external CSS file. You do this using the <link> element in the <head> section of each HTML page:

<head>
	<title>Example Page</title>
	<link rel="stylesheet" type="text/css" href="style.css" />
</head>