Introduction to CSS

Peter Coxhead [1]

Contents

 1 Introduction
 2 Selectors
 3 Properties
 4 Values and Units
 4.1 Numbers
 4.1 Percentages
 4.3 Colours
 4.4 Size units
 4.5 URLs
 5 Inheritance and Cascading
 6 Style elements in HTML
 7 The Box Model
 8 Positioning
  References/Bibliography

1 Introduction

Consider the very simple XHTML document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>CSS Example 1-1</title>
  </head>
  <body>
    <h1>CSS Example 1-1</h1>
    <p>This is a very simple <span>example</span> of a web page in XHTML.</p>
  </body>
</html>

Opening this in Firefox produces a page which looks like this:

The appearance of the page -- the font face, font sizes and layout -- are generated by the browser (although they depend to some extent on what preferences have been set by the user).

The use of 'Cascading Style Sheets' (CSS) offers a principled way in which to alter the appearance of a web page. The broad idea of CSS is to attach 'styles' to HTML elements -- either to individual elements or to groups of elements.

Suppose we want all the text in the p (paragraph) element in the example above to be in italics. First we have to create a 'style sheet'. This can be in a separate document or it can be embedded in the XHTML page. Initially, we'll choose the latter approach. CSS style rules are placed in the head element, using a style element with the attribute type="text/css". A rule consists of a 'selector', which picks out HTML elements, and a style description, enclosed in braces { }. Here we want to say that any paragraph should have the font style italic. The required insert into the XHTML page (immediately after the title element) is:

    <style type="text/css">
      p { font-style: italic; }
    </style>

This produces the web page:

Notice that the contents of the span element inside the paragraph are also in italics. This illustrates a general principle of CSS: child elements inherit appropriate styles from their parent element. We can override this inheritance by specifying a style for the span element. At the same time we'll make the heading smaller.

    <style type="text/css">
      p { font-style: italic; }
      span { font-style: normal; font-weight: bold; }
      h1 { font-size: 120%; }
   </style>

As rendered by Firefox, this produces:

(The h1 element is rendered in a smaller font size than before because the 120% is relative to the default font size for all text, not to the size previously chosen by the Firefox.)

A better alternative to embedding CSS into a web page is to put it into a separate file. A link element in the HTML is then used to specify the URL of the file:

<link href="URL-of-CSS-document" type="text/css" rel="stylesheet" />

The URL can be relative (and is then resolved relative to the HTML document) or can use the http: or file: protocols.

CSS is not restricted to HTML; it can also be applied to XML. Here we MUST put the CSS into a separate document. In some ways, CSS is easier to learn and understand when applied to XML. This is because HTML already has a large set of default styles which browsers[2] apply automatically. Styles defined by CSS add to and/or override these, which can make it difficult to work out exactly what is happening. By contrast, browsers apply little or no default styling to XML.

Consider the simple employees XML document we used in "Valid XML and DTDs", §1. We'll add a stylesheet:

<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="employees.css"?>
<employees>
  <employee>
    <firstname>Joe</firstname><familyname>Bloggs</familyname>
    <comment>Due to retire soon.</comment>
  </employee>
  <employee>
    <firstname>Ravi</firstname><familyname>Patel</familyname>
    <comment/>
  </employee>
</employees>

To begin using CSS to style this document, we can define the font to be used throughout by attaching it to the root employees element. It will be inherited by all the children of employees. We'll use Arial (or some other sans-serif font if Arial is not available) in 12 point size:

employees { font-family: Arial, sans-serif; font-size: 12pt; }

Next we need to say that an employee element is a 'block level element' -- it should start a new block of text (in particular, a new line), leaving some space at the top and left. (The reason for the choice of units below will be explained in §4.4.)

employee { display: block; margin-top: 0.5em; margin-left: 0.5em; }

Finally we'll define some styles for the elements of employee. These should be 'inline' (i.e. they don't start a new line), but should have some space to their right to separate them. We'll also make the comment a bit smaller:

firstname, familyname, comment { display: inline; margin-right: 0.5em; }
comment { font-size: 80%; }

We almost certainly don't need to say that these three elements are inline, since this is usually the default, but it does no harm and will be clearer to the reader. Note that percentage sizes for fonts are relative to their default inherited size, so the actual font size of the comment should be 80% of 12pt ~ 10pt.

With all the CSS collected together into a file named employees.css as per the xml-stylesheet processing instruction, Firefox renders the employees XML document (which is at http://www.cs.bham.ac.uk/~pxc/web/infoweb/employees.xml) as:

My selection of core CSS properties and their values is given in "Core CSS Properties & Values". In the rest of this document, I will concentrate on explaining some of the general principles behind CSS.

2 Selectors

Selectors pick out the relevant elements to which a given style rule is to be applied.

*

Matches any element. However to apply a style to every element, it's often better to apply it to the root element (or body in HTML) and allow it to be inherited if appropriate.

E

Matches any E element (i.e. any element whose name is E). This is the basic selector.

A E

Matches any E element that has an A element as its ancestor. A may be the parent of E, but can also be the grandparent, great-grandparent, etc.

P > E

Matches any E element that is a child of an element P. Here P must be the direct parent of E.

S + E

Matches any E element immediately preceded by a sibling element S.

E[foo]

Matches any E element which has a foo attribute, whatever its value.

E[foo="bar"]

Matches any E element whose foo attribute value is exactly equal to "bar".

E[foo~="bar"]

Matches any E element whose foo attribute value is a list of space-separated values, one of which is exactly equal to "bar".

E.bar

In HTML, the same as E[class~="bar"]. Doesn't work when styling XML.

E#myidval

Matches any E element with an attribute of type ID (but of any name) with the value "myidval". In XHTML, the attribute id is pre-declared to be of type ID, so is normally the one used with this selector pattern.

Any of the above selector patterns can have one 'pseudo-element' appended to the end of the pattern. A pseudo-element starts with a colon.

:first-child

Matches only if the otherwise selected element is also the first child of its parent.

:link
:visited

Matches only if the otherwise selected element is also the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited).

:active
:hover
:focus

Matches only if the otherwise selected element is also currently undergoing the appropriate user actions (e.g. :hover is normally true if the mouse is over the display of the element). Used to produce dynamic changes in styles.

The 'qualifications' are applied separately rather than sequentially in selecting an element. For example div[class~="bar"]:first-child selects any div which has the class attribute containing the value "bar" and which is also the first child of its parent. It doesn't first select all divs with the correct value of the class attribute and then select the first of these.

Finally, these 'simple' selector patterns can be combined.

Pat1, Pat2, ...

Matches whatever selector pattern Pat1 matches or whatever selector pattern Pat2 matches, etc. Note that the comma separates whole sub-patterns. Thus to match any E element or any F element where both have ancestor A, we must write A E, A F. The pattern A E, F matches any E element whose ancestor is A or any F element regardless of its ancestor.

(A few other patterns will be found in the CSS 2.1 standard (W3C 2007), particularly those concerned with matching elements marked as being in specific human languages.)

3 Properties

We noted in §1 that a style rule consists of a selector followed by a body enclosed in braces { }. The body consists of a list of pairs of the form 'property: value', separated by semicolons, such as in:

employee { display: block; margin-top: 6pt; margin-left: 6pt; }

Layout is not significant, but for readability should be consistent. I either use the single line style above, or the following:

employee
{ display: block;
  margin-top: 6pt;
  margin-left: 6pt;
}

The final semicolon isn't necessary, but experience shows that leaving it out results in errors when extra pairs are added later.

As noted above, a selection of core CSS properties and their values is given in "Core CSS Properties & Values".

4 Values and Units

CSS uses a number of values. Some are just names (like block or inline, for example). Others involve types and units. An overview of some of these is given below.

4.1 Numbers Integers and floating point numbers, both positive and negative, are allowed. Syntax is an optional minus sign, followed by digits, and, optionally, a decimal point followed by digits.

4.2 Percentages are represented by a number followed by a percentage sign. What exactly the percentage is of depends on the property. Often it is the value that would otherwise be the inherited default. If in doubt, use the CSS 2.1 reference (http://www.w3.org/TR/CSS21/).

4.3 Colours There are a number of ways to specify colour values in CSS:

Web safe colours are colours that will generally be displayed correctly on most computer systems. These are ones that don't require dithering on low colour systems (i.e. using a mixture of pixels of different colours to fill an area in order to give the impression of a colour that cannot be represented by pixels of a single colour). Such web safe colours are those which, in hexadecimal, have each component limited to multiples of 3: 00, 33, 66, 99, CC or FF. Thus #FC0 is web safe. A selection of web safe colours will be found at
http://www.cs.bham.ac.uk/~pxc/web/colours.html.

4.4 Size units There are a number of different units for sizes used in CSS. These can be divided into absolute units and relative units.

Absolute units include inches (e.g. 1.5in), centimetres (e.g. 3.2cm), millimetres (e.g. 7mm), and points (e.g. 12pt). Points are defined in CSS to be 1/72 of an inch. However don't expect browsers to respect this when points are used to define font sizes because of the complex interaction between the preferences/defaults set by the user, the style information and how the operating system renders text.

Absolute units should generally be avoided wherever possible. Browsers allow the user to increase or decrease the size of text for legibility. Other features of the displayed page should usually change size along with the text. For example, a 6pt space (1/12in) is fine to separate blocks of text initially presented in 12pt size, but will no longer visibly separate them if the user scales up the text by a factor of 8.

Relative units include the em and the ex. These are taken, in principle, from typography, where an em corresponds to the width of a letter 'm' in the current font and an ex corresponds to the height of a letter 'x' in the current font. However, CSS changes the meaning of these units. In CSS, an em is the size of the font, i.e. the height of the font, not the width of the letter 'm'. An ex is still supposed to be the height of the letter 'x', but because this information is not always available from a font, a default (which is usually wrong) is to make it half an em. Ems are almost always the best unit to use in defining layout since they scale with changes in text size.

A pixel (px) in CSS is also defined to be a relative unit. That is, it is not a actual pixel (dot) on the output device. Screens nowadays have resolutions in the region of 100dpi whereas printers often have resolutions of 300dpi, 600dpi or even higher. If you printed out a document where the layout had been specified in true pixels, then you would get a very tiny cramped image. Hence the CSS standard defines a "reference pixel" to correspond to 96dpi, and states that if the display device is "significantly" different from this then the unit must be scaled. Thus a 1px square can be shown on a 96dpi screen as a single pixel, but would be scaled to a 3x3 grid of pixels on a 300dpi printer. The reality, especially when displaying and printing bit-mapped images, is more complicated, and results will vary between browsers and operating systems.

Conclusion As far as possible, use em units or percentages for most lengths, except for 'top level' definitions, e.g. the base font size or the page size. Margins, padding, border widths, etc. should all be specified relative to the font size (using em units) or to the sizes of parents (using percentages). Only bit-mapped images need to be specified in pixels, but don't expect absolute conformity across browsers and operating systems.

4.5 URLs are specified with the syntax url(URL-string), where URL-string is replaced with a valid URL string which can be absolute or relative. If relative, it is relative to the location of the CSS style sheet, not to the HTML document that uses the stylesheet.

5 Inheritance and Cascading

Elements inherit many styles from their parent elements. Thus in the employees XML example discussed in §1, the font styles set for the employees element were automatically applied to the employee elements, and then inherited in turn by the firstname, familyname and comment elements. At any stage, the inherited values can be overridden by a style rule for an element, whereupon its children will inherit the new style.

The only real complication is that not all properties are inherited, for good reasons. Consider the CSS we used to style the employees XML document:

employees { font-family: Arial, sans-serif; font-size: 12pt; }
employee { display: block; margin-top: 0.5em; margin-left: 0.5em; }
firstname, familyname, comment { display: inline; margin-right: 0.5em; }
comment { font-size: 80%; }

The margin properties (margin-top, margin-left) set on the employee element are meant to space out each of those elements from the next. We don't want all the child elements to have the same margin properties, since this would continually introduce extra spacing with each level of the element hierarchy. Hence CSS defines margin properties as not inheritable.

Generally, then, whether a property is inherited is what you would expect. In cases of doubt, the table starting at p377 of the PDF version of the CSS 2.1 standard
(http://www.w3.org/TR/CSS21/css2.pdf) specifies whether a property is inherited or not.

An important design feature of CSS was that it should be useful in styling large web sites. In this situation, there are likely to be general styles which should be applied throughout, with more specific ones for particular parts of the site. This effect can be achieved by the use of import statements, which can have either of these two precisely equivalent formats:

@import "URL-for-CSS-document";
@import url("URL-for-CSS-document");

When the URL is relative, it is resolved relative to the CSS document in which the import statement appears. Import statements must appear before all rule sets in the CSS document. The imported document may itself contain import statements; hence there may be a 'cascade' of styling information.

How style rules are put together for a given element and which rule takes precedence is a very complex topic; refer to the CSS 2.1 standard (W3C 2007). Some GENERAL principles are:

However, there are ways of altering the expected cascade order, e.g. by declaring a style rule to be important. Refer to the CSS 2.1 standard (W3C 2007).

6 Style attributes in HTML

We have looked at two ways of supplying CSS style information.

In HTML documents, styles can be supplied for individual elements via a style attribute, e.g.:

<p style="font-weight: bold;">It is extremely important to note that ...
</p>

Given the general principle that later style definitions override earlier ones, if there is a conflict, the style attribute will override any other style definitions present for that element.

Using style attributes should normally be avoided in permanent documents, although it can be useful in developing and debugging style sheets. It violates the principle of separation and makes web pages much harder to maintain, particularly in large web sites with multiple authors. Someone changing a site-wide style sheet won't expect to find that some elements in seemingly random pages don't change appearance because the page author has included a style attribute. The best approach by far is the use of external style sheet documents -- this is enforced for XML documents.

7 The Box Model

'Block' elements in CSS can be described by a box model. The innermost part is a box containing the actual content, e.g. text, images or a mixture of both. The content has a height and a width, which can be specified by CSS properties or determined automatically. A border may be placed around the content. The distance between the inner edge of the border and the edge of the content is determined by the amount of padding. Padding is the space between the border and the content, which prevents the content from touching the border. Finally, to prevent two adjacent block elements from merging together, a margin may be specified. The margin is the space between the border and the nearest point that the border of an adjacent box may be placed.

The padding, border and margin may all be of 0 width (i.e. not present), and may be of different widths on all four sides (see "Core CSS Properties & Values" for how to achieve this).

To show how this works, we'll apply the following CSS to the employees XML given in §1 above:

employees { font-family: Arial, sans-serif; font-size: 16pt; }
employee
{ display: block;
  background-color: silver;
  padding: 0.5em;
  border: solid black 1em;
  margin: 0.5em;
}
firstname, familyname, comment { display: inline; margin-right: 0.5em; }
comment { font-size: 80%; }

This produces the display shown below (reduced to 60% of its original size).

Points to notice about the way the employee elements are shown are:

The best way to understand the box model is to play with it, changing widths, background colours, etc. while predicting and observing the changes. You can download the employee XML document from http://www.cs.bham.ac.uk/~pxc/web/webinfo/employees.xml, and experiment by downloading the CSS file at
http://www.cs.bham.ac.uk/~pxc/web/webinfo/employees-rev.css and altering the employees XML document to use this CSS document.

8 Positioning

This is one of the most complex aspects of CSS, and the part of the standard still least respected by browsers. Extensive testing is normally needed before using CSS for complex positioning in public web pages. The four kinds of positioning available will be briefly described. More complex usage is beyond this module. (See also "Introduction to JavaScript for Java Programmers", §14).

Static In all the examples of CSS so far, we have allowed the browser to determine the relative position of the components of the display. The most we have specified is part of the size of each component (through padding and border properties, for example) and the spacing between them (through margin properties). We have not attempted to put components into specific positions in the display. This is the default kind of positioning in CSS, so-called 'normal flow'. If normal flow has to be specified explicitly then it is achieved by including position: static in a style rule. [I find this a misleading name, since I expect 'static' positioning to mean a fixed position on the page, but it doesn't.]

Relative In relative positioning, we first allow the browser to determine the normal flow position of an element and then offset it relative to this position. The offset is specified by the top, right, bottom and left properties. Typically, only two will be given. (Later when we study JavaScript, we will see how animation effects can be produced by dynamically changing the offset of relatively positioned elements.)

Relative positioning is probably the most useful alternative to the default normal flow positioning indicated by position: static, since we don't have to go to the length of working out exactly where an element will 'fit' among the other displayed elements. On the other hand, we can use an appropriate offset to adjust its position, perhaps to mark it out in some way. For example, in displaying a list of employees from an XML document, we might want to shift all the lines displaying managers slightly to the left, in order to pick them out. Having defined a standard way of displaying employees, say in a file called employees-standard.css, the required CSS could be placed in a file called employees-extra.css:

@import "employees-standard.css"
employee[status="manager"]
{ position: relative;
  left: -1em;
}

To see the effect of this CSS, open the file
http://www.cs.bham.ac.uk/~pxc/web/webinfo/employees1.xml in Firefox. If you download this file and the associated style sheet documents, you can experiment with different settings.

Absolute In absolute positioning, we don't allow the browser to determine the position of an element at all. Instead we specify the position relative to the element's containing block, using the top, right, bottom and left properties. The complexity comes in determining what the 'containing block' is. Often this will be the box within which the parent element is displayed. More precisely it is the display box of the nearest ancestor whose position is relative, absolute or fixed. [Again I find this a misleading name; the positioning is not absolute, but relative to the containing block. In CSS, relative positioning is relative to where the browser would otherwise have placed the element; absolute positioning is relative to the element's container.]

Fixed In fixed positioning, the position of the element is fixed relative to the 'display': typically the window when on screen and the page when printed. Thus elements with fixed position don't scroll when displayed on screen. Again the position is specified by the top, right, bottom and left properties. Fixed positioning can be used to create features such as menus which should be constantly present on the screen, regardless of the degree of scrolling. In practice, variable browser support at present makes it difficult to use reliably.

References/Bibliography

See the other handouts for this module, which are available online.

Goodman, Danny (2007). Dynamic HTML: The Definitive Reference. O'Reilly. 0-596-52740-3. [This is an excellent and detailed reference manual for browser compatibility of all kinds of HTML, CSS, Javascript, and DOM related issues. However, it is purely a reference and not suitable for learning these topics in the first instance.]

Lie, Håkon Wium & Bos, Bert (2005). Cascading Style Sheets: Designing for the Web (3rd ed.). Addison Wesley. 0-321-19312-1. [Written by the original creators of CSS, this book is very readable with plenty of examples. It is not complete but contains enough for all except the most demanding of CSS design projects. An excellent beginners text on CSS 2.1.]

Meyer, Eric A. (2006). CSS: The Definitive Guide (3rd ed.). O'Reilly. 0-596-52733-0. [A detailed, excellent coverage of CSS. It can be a somewhat of a heavy read and hence daunting to a beginner in CSS.]

W3C (2007). Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. http://www.w3.org/TR/CSS21/. [CS2.1 Specification; quite readable.]

Wilson, Brian (2003). Index DOT Css. http://www.blooberry.com/indexdot/css/. [There are very few online CSS references that are of high quality. This is one of them.]

Footnotes

[1] This document is based on an original by Alan Sexton © 2007, modified by permission.

[2] The term 'browser' is used here as a shorthand for the more accurate 'visual user agent'.

GoHome Page for "Information and the Web"