(X)HTML Tutorial

Cascading Stylesheets (CSS)

Web pages rarely consist of pure (X)HTML code these days because the formatting capabilities of (X)HTML are very limited--more so, if the author conforms to best practices for semantic coding. Cascading Stylesheets (CSS) is a language which enables the separation of content from presentation formatting. This allows for different renderings of the same markup in different circumstances. For instance, one could use CSS to display all links in blue on a web page but not in print (since it is not possible to click on a link on a printed page).

The term "stylesheet" refers to the fact that styling information can be placed at the beginning of the (X)HTML document or in another file altogether, where it governs the styling of the entire document. It is also possible to use the CSS language for inline styling--that is, styling individual elements at their point of occurrence--and this is the easiest way to begin learning CSS. The term "cascading" refers to the fact that there is a priority scheme for which CSS rules take precedence when multiple rules apply to the same element. The easiest aspect of this cascading effect to understand is that the rule given last has priority over any rules given previously. So if a CSS rule specifies that text should be red and, in the next line, a rule specifies that it should be green, the text will be green.

CSS rules are expressed in the form of a property and a value, separated by a colon. For example, the declaration color: green will make the text appear green. Multiple declarations can be given separated by semicolons (which are commonly used to indicate line breaks in programming). For instance, color: green; font-weight: bold; will render the text green and bold. (The semicolon after "bold" is not necessary but is often added as a matter of convention.)



Inline Styling Using CSS

For inline styling, (X)HTML has a"style" attribute (@style) which invokes the CSS language. Consider the following example:


<p>This is a paragraph containing some text in <span style="color: green">green</span>.</p>

This will appear as

This is a paragraph containing some text in green.

@style can be applied to any (X)HTML element.


Using Stylesheets

What if you wanted to make all your paragraphs display in a larger font than the browser's default font? The CSS rule for this would be font-size: larger. However, you would not want to type <p style="font-size: larger;"> for every paragraph in your document. A better way to achieve this effect is with a stylesheet. This is a set of CSS declarations given in the document's <head> element. (X)HTML has a special element, the <style> element, used to place a stylesheet in a document. Here is an example of a complete web page with a stylesheet.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <title>Document Title</title>
   <style type="text/css">
      p { font-size: larger; }
   </style>
   </head>

   <body>
      <p>The font size of this paragraph is larger than the browser's default size.</p>
   </body>
</html>

And here is how this page will look:

The font size of this paragraph is larger than the browser's default size.

The syntax for stylesheets is simple. Inside the <style> element there is a list of selectors. The properties of each selector and their values are listed inside curly brackets. CSS selectors are frequently (X)HTML elements (listed without angular brackets). So, in the example above, the stylesheet consists only of the (X)HTML <p> element.


Using External Stylesheets

CSS stylesheets are sometimes very long, which can make it more convenient to save them in a separate file. This is especially useful if you wish to use the same stylesheet for more than one web pages. (X)HTML has a method of liking web pages to stylesheets in separate files. In the <head> element, include the following code:

   <link href="stylesheet.css" rel="stylesheet" type="text/css" />

Replace stylesheet.css with the name of your stylesheet file (which conventionally ends in .css).

Using the method described above, it is possible to override the browser's default styling rules for any (X)HTML element.


Making Your Own CSS Rules

What if your document consisted of a series of paragraphs representing a dialogue between two speakers. You might wish to represent Speaker 1's speech in blue and Speaker 2's speech in green. One way to do this would be to set up a CSS class for each speaker. CSS classes are indicated in the stylesheet by the presence of a dot before the CSS selector. In the (X)HTML, the name of the CSS class is given (without the dot) inside a class attribute. Here is how it would look in the stylesheet:


   .speaker1 {color: blue;}
   .speaker2 {color: green;}

In your (X)HTML, you would then have:


   <p class="speaker1">Speaker 1 says something</p>
   <p class="speaker2">Speaker 2 says something</p>

The first paragraph would display in blue and the second paragraph in green. Using the speaker1 and speaker2 classes, it would be possible to specify which paragraphs should be blue and which paragraphs should be green throughout the document.

Here's another scenario. You have a document consisting of a table of contents and a text. You want the table of contents to display in blue, not the default black. You could create a .table_of_contents class to achieve this effect. However, the scenario is a little different from the example above since your document has only one table of contents. In this case, you might want to represent your document's structure semantically as follows:


   <div id="table_of_contents">
      <p>Chapter 1</p>
      <p>Chapter2 </p>
   </div>
   <div id="text">
      <p>Text goes here</p>
   </div>

Notice that each <div> element has an id attribute attached. The text of each unique <div> can be styled individually in the stylesheet. So the "table_of_contents" <div> might have the following declaration:


   #table_of_contents {color: blue;}
   

Notice that in the stylesheet the id of the <div> element is preceded by #, and, in the (X)HTML it is contained within the attribute @id.


Learning CSS

CSS is a very rich language, and it can take some time to learn all the various properties and their possible values. Some of the more common and useful ones will be described in this tutorial. There are many tutorials devoted specifically to CSS available online. However, it is often easiest to identify what you want to do and then type into a search engine, "How to do I do X using CSS?" You'll will almost always find the answer you are looking for.


The CSS Box Model

One important aspect of CSS needs a full discussion before we return to (X)HTML. Normally, a paragraph of text will stretch all the way from the left side of the screen to the right side before wrapping to the next line. This can result in a distracting "clipped" appearance. Occasionally, your text may be too close to something else on your page as well. For instance, imagine the box below as the browser window.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer suscipit enim magna, ac dictum augue. Quisque blandit, mi quis pulvinar blandit, purus sem blandit eros, non porta justo massa ut nisi. In hac habitasse platea dictumst. Pellentesque fermentum gravida nunc ut auctor. Suspendisse quis risus vel tellus congue imperdiet. Morbi vitae mauris neque. Vivamus ut lorem sem, in facilisis purus. Mauris quam nunc, interdum sit amet ultricies ac, faucibus eget lorem. Phasellus tempor suscipit neque, vel cursus lacus volutpat quis. Proin feugiat lacus vel eros rhoncus et varius arcu rutrum. Vivamus sapien lorem, ullamcorper eget luctus a, placerat at eros. Phasellus aliquam varius mauris, quis condimentum est fermentum vitae. Cras varius velit eu massa fringilla porta. Vivamus a porttitor neque. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam adipiscing dictum pharetra. Phasellus et ipsum at leo rhoncus posuere.

See how close the text is to the border? How would we create a margin so it looks like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer suscipit enim magna, ac dictum augue. Quisque blandit, mi quis pulvinar blandit, purus sem blandit eros, non porta justo massa ut nisi. In hac habitasse platea dictumst. Pellentesque fermentum gravida nunc ut auctor. Suspendisse quis risus vel tellus congue imperdiet. Morbi vitae mauris neque. Vivamus ut lorem sem, in facilisis purus. Mauris quam nunc, interdum sit amet ultricies ac, faucibus eget lorem. Phasellus tempor suscipit neque, vel cursus lacus volutpat quis. Proin feugiat lacus vel eros rhoncus et varius arcu rutrum. Vivamus sapien lorem, ullamcorper eget luctus a, placerat at eros. Phasellus aliquam varius mauris, quis condimentum est fermentum vitae. Cras varius velit eu massa fringilla porta. Vivamus a porttitor neque. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam adipiscing dictum pharetra. Phasellus et ipsum at leo rhoncus posuere.

There is actually more than one way to achieve this effect. In order to understand how, you need to understand the CSS Box Model. Imagine every element on the screen as occupying a box. There is a space outside the box frame called the margin and a space inside the frame called the padding. The <body> tag is element on the screen, so what if we did this in our stylesheet?

 
    
   body {margin: 50px; padding: 50px;}
	 
  

Since everything on our web page is inside the <body> element, we have now placed 50 pixels of space (the margin) between our content and the edge of the screen. Since we have also put 50 pixels of space inside the <body> element (the padding), there will actually be 100 pixels of space between our content and the edge of the screen.

So that's one way to do it. Another way is to use a <div> element as a wrapper and style that. For instance, what if we put the following in our stylesheet?

 
    
   #wrapper {margin: 50px; padding: 50px; border: 1px solid black;}
    
  

Inside of our body, we would put the following:

 
   <div id="wrapper"> <p>Lorem ipsum, etc.</p> </div> 
  

This will look exactly the same as if we had styled the <body> element, except that this time we have added a black border.

In case you haven't guessed, that's how we get the boxes displayed above. The following code is placed inside the stylesheet (either in the <head> element of the document or in an external file):

 
   #box {margin: 50px; padding: 50px; border: 1px solid black;}
    
  

And in your (x)html, something like this:

 
    
   <p>Some text</p>
   <div id="box"> <p>Lorem ipsum, etc.</p> </div>  
   <p>Some more text</p>
    
  

Note that this method should be used only if you want each box to be semantically unique. For instance, say you have a box containing an Old English text and a box containing the translation. You might have the following code in your stylesheet and (X)HTML:

 
    
   #old-english {margin: 50px; padding: 50px; border: 1px solid black;}
   #modern-english {margin: 50px; padding: 50px; border: 1px solid black;}

   <div id="old-english"> <p>Some Old English text</p> </div>  
   <div id="modern-english"> <p>The translation</p> </div>  
    
  

However, is you had multiple boxes for each (for instance, if you were displaying multiple extracts, it would be better to use a CSS class. So your code would look like this:

 
    
   .old-english {margin: 50px; padding: 50px; border: 1px solid black;}
   .modern-english {margin: 50px; padding: 50px; border: 1px solid black;}

   <div class="old-english"> <p>Some Old English text</p> </div>  
   <div class="modern-english"> <p>The translation</p> </div>  
    
  

The appearance will be the same, but you can use the CSS class for more than one box.

You can also fix the width of your box using the CSS:

 
    
   #box {width: 250px; margin-left: auto; margin-right: auto; padding: 15px; border: 1px solid black;}
    
  

This will give you:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer suscipit enim magna, ac dictum augue. Quisque blandit, mi quis pulvinar blandit, purus sem blandit eros, non porta justo massa ut nisi. In hac habitasse platea dictumst. Pellentesque fermentum gravida nunc ut auctor. Suspendisse quis risus vel tellus congue imperdiet. etc.

Here we tell the browser to calculate the distance from the edge of the screen automatically so that the box appears in the centre. In addition to margin-left and margin-right, you can also specify margin-top, margin-bottom, padding-left, and so on. There's even a shorthand: margin: 1px 2px 3px 4px indicates margin-top: 1px; margin-right: 2px; margin-bottom: 3px; margin-left: 4px (it goes clockwise).

These CSS techniques seem straightforward, but they are a very simplified account of the CSS box model. You should be aware that the box model is not implemented the same way by every browser (especially older ones), causing endless headaches for web designers. Internet Explorer 6 is notorious. Here is a full, and fairly readable account of the box model and CSS positioning.


Problems with CSS

CSS is very powerful and can be used for the layout of whole web pages, as well as for styling the appearance of text. However, it does have limitations. One of the most significant is that it is inconsistently implimented in different browsers. Just because your CSS achieves the appearance you want in one browser does not mean that it will appear the same in another. In particular, the CSS box model is implemented somewhat differently amongst the various popular browsers, despite attempts in recent years to make them conform to common standards. There is a great deal of literature available on the web concerning how to deal with the inconsistent implementation of CSS.

Return to Top