Sunday, 7 September 2014

Introduction to CSS

The ubiquitous Cascading Style Sheets (CSS) is used in web pages to separate content from formatting.

As usual, we begin with an example. Prepare myhtml.html in your favourite text editor:

<!DOCTYPE html>
<html>
    <head>
        <title>Example Page Using CSS</title>
    </head>
    <body>
        This page is not using <b>CSS</b>!
    </body>
</html>

Then, open myhtml.html in your favourite browser. You should see the following, which is expected as b is the HTML tag for bold:

This page is not using CSS!

Now, create another file, mystyle.css:

b { color: red; text-decoration: underline; }

And add a new line to myhtml.html and change the body text:

<!DOCTYPE html>
<html>
    <head>
        <title>Example Page Using CSS</title>
        <link rel="stylesheet" href="mystyle.css">
    </head>
    <body>
        This page uses <b>CSS</b>!
    </body>
</html>

Now, you would see the following instead:

This page uses CSS!

Perhaps that was unexpected - what happened to the bold attribute? As it turns out, CSSes are a great way to separate content from formatting. Suppose we had several static web pages (not using CSS), and one day we decided to give the website a facelift. It would have been a chore hunting down all the instances of a specific formatting! With CSS, only a single location would have to be changed. A suitable analogy would be the styles feature in Microsoft Word. Let's try changing the formatting in mystyle.css:

b { color: blue; }

The web page looks like the following instead:

This page uses CSS!

Of course, instead of the tag b we would use a more distinctive name. Well, that was easy! Check out further reading here: CSS Home Page on the W3C

No comments:

Post a Comment