Styling Your HTML With CSS

In this article I cover ways to style your content using various methods. All coding practices adhere to HTML 4 strict doc type though the CSS level is not important. The main thing is that the <font> tag will not be used. Ever!

There are a number of ways to style your text within an HTML document. The most obvious choice is to use inline styles. An example of this is:

<p style="color: #F00;">This is some text</p>

This outputs the following:

This is some text


I have chosen this method as the first example as no matter how you include your styles, with the exception of DOM, this method will override all other methods..

The other methods that follow all should be placed with the <head> of your HTML document. The second method would be to include inline style within the <head> as described. Example:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    <style type="text/css" media="all">
    <!-- 
    p { color: #F00; }
    -->
    </style>
</head>
<body>
    <p>This is some text</p>
</body>
</html>


This once again outputs:

This is some text


The final 2 methods use external styles-sheets - otherwise known as CSS. This is perhaps the best method as changes made to the external file take affect site wide thus minimizing changes required on the actual HTML documents. The 2 methods are shown in the example below. They can be used simultaneously to include multiple CSS files. Note that the order that the styles are called within the document affect the style rules that you may have in place. This is called style precedence!


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    <!-- method 1 @import -->
    <style type="text/css" media="all">@import "style.css";</style>
    <!-- method 2 relative link -->
    <link rel="stylesheet" type="text/css" href="print.css" media="print">  
</head>
<body>
    <p>This is some text</p>
</body>
</html>


To stay in keeping with the rest of the code in this article, the only styling that is used elsewhere is p { color: #F00; }. Nothing else. Notice the differences too in the above example with media. This gives you an option to select a style-sheet for the device you are targeting. In the example above I used media="print". This is a print style-sheet. Try print previewing this site to see the differences between the web and print versions.

This has been a very basic introduction to styling. There are millions of articles out there. I hope to add to the millions with a few more quality ones of my own over the coming months.

Syndicate content