Article

CSS Is Easy!

Page: 1 2 3 4 5 6 Next

Defining Styles with CSS

The basic principle of CSS is to allow the designer to define a style (a list of formatting details like fonts, sizes, and colours) and then apply it to one or more portions of one or more HTML pages using a selector. Let’s look at a basic example to see how this is done.

Consider the following HTML document outline:

<HTML>
<HEAD>
<TITLE> A simple page </TITLE>
</HEAD>
<BODY>

<H1><FONT FACE=”sans-serif” COLOR=”#3366CC”>First Title</FONT></H1>
<P>...</P>

<H1><FONT FACE=”sans-serif” COLOR=”#3366CC”>Second Title</FONT></H1>
<P>...</P>

<H1><FONT FACE=”sans-serif” COLOR=”#3366CC”>Third Title</FONT></H1>
<P>...</P>

</BODY>
</HTML>

This document contains three headings, created using <H1> tags. To make these headings stand out more, I have used <FONT> tags to make them light blue in a sans-serif font (Windows browsers will display them in Arial, for example). Notice the repetition involved, even at this basic level. I had to specify the details of the font I wanted three separate times. Wouldn’t it make sense to define the font just once and then apply it to my headings? Here’s the CSS version:

<HTML>  
<HEAD>  
<TITLE> A simple page </TITLE>  
<STYLE TYPE=”text/css”>  
<!--  
 
H1 {  
 font-family: sans-serif;  
 color: #3366CC;  
}  
 
-->  
</STYLE>  
</HEAD>  
<BODY>  
 
<H1>First Title</H1>  
<P>...</P>  
 
<H1>Second Title</H1>  
<P>...</P>  
 
<H1>Third Title</H1>  
<P>...</P>  
 
</BODY>  
</HTML>

All of the magic is between the <STYLE> tags in the <HEAD> of the document, where we define our light blue, sans-serif font and apply it to the <H1> tags in the document. Don’t worry about the syntax; I’ll explain it in detail in a moment. Meanwhile, the <FONT> tags have completely disappeared from the <BODY>, leaving our document looking a lot less cluttered. Changes to the style definition at the top of the page affect all three headings, and any other headings added to the page will also take on the style.

Now that you’ve got some idea of what CSS does, let me explain the different ways of using CSS styles in your HTML documents.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links