4.2Why CSS exists

Separating content and styling

As the Web grew in popularity in the 90s, the intent to apply a specific design to a website grew as well. Web developers relied upon specific HTML tags to enhance webpages:

<basefont> defined a font for a whole HTML document

<font> defined a typeface, a color, and a size for the text it contains

<center> horizontally centered all its content

<big> increased the size of the text

<strike> rendered text with a strikethrough

Several HTML attributes could also be used:

bgcolor defined a background color on the element

text defined the text color

several margin attributes could be used to add space on any side of the element

Why avoid tables

But most of all, in order to create columns, visually align elements, and generally position elements relatively to each other, Web developers used the <table> element to design their webpages because it naturally provided a visual grid:

How CSS works

How CSS works is by selecting an HTML element (like a paragraph), choosing a property to alter (like the color), and applying a certain value (like red):

p{color:red;}

The word “Style” can be deceiving. You might think CSS is only used to change the text’s color, size, and font. But CSS is able to define an HTML document’s layout, by defining heights, widths, inner and outer margins, positions, columns…

Where do I write CSS?

CSS as an attribute

You can write CSS directly on an HTML elements, by using the style attribute:

CSS in a separate file

You can write your CSS in a separate file with a .css extension, and then link it to your HTML by using the <link> HTML tag.

p{color:red;}

<html><head><title>Hello World</title><linkrel="stylesheet"type="text/css"href="style.css"></head><body><p>This paragraph will be red.</p></body></html>

It is the HTML document who “calls” the CSS file, in this case a file called style.css located in the same folder as the HTML file.

This 3rd method of using a separate CSS file is preferred.

Why not style directly in the HTML?

Because we want to separate the content (HTML) from its presentation (CSS).

If you want to visualize the purpose of this distinction, head towards the wonderful CSS Zen Garden: each design uses the exact same HTML but a different CSS each time.

It makes maintenance easier as well: the same CSS file can be used for a whole website. It provides flexiblity: focus on the content on one side, the styling on the other. SEO purposes, different concerns.