• Objectives of this page
  • Prerequisites for those using it
  • Basic terms used for styles
  • Style declarations
  • Style rules
  • Inline styles
  • Classes and ids
  • Contents of stylesheets
  • Internal and external stylesheets
  • Multiple stylesheets
  • Managing stylesheets

Just a few details of those properties which amy not be self evident

  • Setting styles for text
  • How to specify colour
  • How background works

The essentials of the CSS two and three dimensional box model for html elements

  • Margin
  • Border
  • Padding
  • Content
  • Overflow
  • Margin collapse
  • Clockwise convention
  • Shorthand convention
  • Centring the box

Using pseudo classes to style links

  • a:link
  • a:visited
  • a:hover

Differences between ‘block.’ and ‘inline’ elements
Introducing the ‘generic’ elements

  • div
  • span

Issues erelating to positioning elements on a page

  • Normal flow
  • Float
  • Realtive position
  • Absolute position
  • Containing blocks

How the various ways of setting up styles interact and which wins if there is a conflict

Terms used on this page

Links to some resources



Show site menu.

This page was composed using Nvu

Subject index


3-d model

Absolute position

Attribute

Background

Block element

Box model

Case sensitive

Centring

Class

Clear

Clockwise

Colours

Comments

Content

Content size

Containing block

Declaration

Div(ision)

Element

Exporting stylesheet

External stylesheet

Float

Fluid design

:hover

id

Inline element

Inline style

Internal stylesheet

Links

Linking stylesheet

Media

Margin (collapse)

Normal flow

Offset

Overflow

Padding

Pseudo classes

Relative position

Rule

Property

Shorthand

Size

Span element

Stylesheet extension

Value

:visited


Introduction to CSS
Cascading Style Sheets

Introduction to CSS
Cascading Style Sheets

1 Preliminary

CSS Cascading Style Sheets is, after html (HyperText Markup Language) the most important language used in designing pages for distribution via the World wide Web.

HTML is the basic underlying language used for every web page; it allows an author to input all the information required to communicate with the visitor. It also allows the significance of the information to be marked in various ways which allows a browser to present it in a suitable way to the visitor. For instance text may be marked as normal paragraphs or headings, images differentiated from text etc.

While HTML does allow some control of the presentation using it in this way is now deprecated by W3C. There are two reasons for this – firstly presentation should be separated from content so that web pages may be understood irrespective of the medium of presentation and secondly, because CSS has so much more power of presentation, retaining the lesser power of HTML is unnecessary and restrictive.

CSS may be employed on any web page and is supported by all modern browsers so that neither the author nor the visitor has to take any particular action. It is true that no browser completely conforms with specifications but this need not be a bar to employing it widely to good effect.

Exercise

Here is an exercise that you can try, it shows just how easy and powerful CSS can be. If you want to try it, copy the following text into a text editor and save it as a file with extension .html Then run it in a browser.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Demonstration</title>
</head>
<body>
<p>This paragraph will, when the designed style has been applied, demonstrate how using only a few lines of code the appearance of a part of a page can be transformed. In this case we are supposing that the author wants to draw particular attention to a paragraph. The style will do four things. 1 - Change the font from the default to a specific font; 2 - Justify the text; 3 - Add a wide, coloured border to left and right sides and a narrow one top and bottom; 4 - Add a margin to each side to move it away from the edge of the page. It also ensures that the text doesn't touch the border by adding some 'padding'</p>
</body>
</html>

That will probably strike you as pretty boring. It doesn't use CSS. Now go back to the text in the editor and add the following just before the end of the head area. That is just before the </head> tag. Save and run in the browser again.

<style type="text/css">
.styled_with_border {
font-family: Arial,Helvetica,sans-serif;
text-align: justify;
border-style: solid;
border-color: #4289b5;
border-width: 2px 3em;
margin-right: 6em;
margin-left: 6em;
padding-right: 1em;
padding-left: 1em;
}
  </style>

What you have done is defined a set of styles and added them to the file. If you save and run the file you will see exactly the same as before — Why? Because though you have defined some styles you haven't used them.

Go back and change the <p> tag to
<p class="styled_with_border">

Run it again. Now you should see what can be done. The style you defined has been applied to the paragraph and the result can be seen in the browser. The result should be something like this.

By modifying the <p> tag for the paragraph by adding class="styled_with_border" we have applied to the paragraph the 'class' which we defined in the head. The paragraph is then formatted using the style definitions found in the head.

Objective

That sounds like a bit of cook book design. It is there just to demonstrate how quick and simple using styles can be and the files are almost self explanatory even to the uninitiated.

This guide is not here to teach cook book stuff; on the contrary I hope the reader will gain a firm basic understanding of the methods and principles involved in using stylesheets. It is an introduction to CSS not a complete guide, so there will be aspects that will simply not be touched on at all. I hope that will prove a strength rather than a shortcoming. By limiting the scope, which is pretty wide anyhow, readers should be able to concentrate on the essentials. Once opened up you should be able to grow your skills in this fascinating area.

Prerequisites

Basic HTML

Text editor

KompoZer

Patience

Let's make it clear. To use this guide you need to be familiar with using your computer including its file system and to have some understanding of HTML. You are not expected to have an in depth knowledge but since CSS is applied through HTML you do need a basic knowledge. If you want to brush up your knowledge of HTML I highly recommend Mark Tranchant's tutorial.

CSS is a simple language and its code can be created using a text editor. We will be showing examples of how the code will look so you may find it helpful to have a text editor available for use.

Even if you are using a wysiwyg authoring tool you will gain a better understanding of how it works and how to use it if you have some knowledge of what it is doing. My favourite is KompoZer with its built in CaScadeS CSS editor. It's 'open source' and will cost you nothing.

Tip

When using KompoZer make sure that you have set Tools > Options > ‘Use CSS styles instead of HTML elements and attributes’.

Where you see the symbol you can click to get details of how to carry out a function being discussed using KompoZer and CaScadeS.

Sometimes you will see the More detail symbol in the margin. By clicking you can get more detail of some complex material or a simpler explanation if that is appropriate.

The operation of the and More detail buttons depends on your browser supporting and having JavaScript enabled. If it does not you can still read everything on the page but some material planned to be initially hidden will be visible all the time.

One other thing you will need is a little patience. You have already seen a demonstration of what styles can do, but to start putting styles to use yourself you need to go through some basics first. If you are using KompoZer this phase will be quite short but if you are handcoding inevitably you need to go a bit deeper because you have nothing except yourself checking your code as you go.

A short refresher on HTML Attributes

ELEMENT

HTML elements are the basic blocks used to build web pages. Examples are 'p' for paragraph 'img' for image. In a file they appear like <p> <img>

ATTRIBUTES

These may be used to modify or qualify elements in some way. Attributes can be assigned to all elements, often this is optional but sometimes it is essential. For example to use an image you must specify the file to be used as the source of the image otherwise nothing will be seen. This is done using the 'src' attribute of 'img'. For example

<img src="images/sheep.jpg">

Note:

  • The attribute appears in the opening tag for the element (as it happens the img element does not have a closing tag.
  • The attribute has two parts—the name (src) and the value (images/sheep.jpg)
  • The value is enclosed in double quotes. (In some very simple cases these may be omitted.)
  • The attribute name and value are connected using an equal sign.

Some attributes, such as the above, are quite specific to particular elements but there are some, of which three concern us, that may be applied to any, yes absolutely any, html element. These are

  • style
  • class
  • id

We will see later how these may be applied but, just to give you an idea, here is one example of each.

<p style="color:red; font-size: small;">Text in a paragraph</p>

<h1 class=centred>This heading is centred</h1>

<p id="footer">This is the footer</p>

Style Basics

Let's look at some basics first. It will be as well to become familiar with some terminology and to learn the syntax.

DECLARATIONS, PROPERTY, VALUE

Styles are applied using style declarations.

A declaration takes the form
property : value
in which a style property is associated with a value by listing them with a colon between.

Key to outlines and colours in use:

Property

Value

Declaration

Some examples are:

color:red
font-size:2em
text-align:center

The properties and values are taken from those specified in the CSS2.1 specification.

It is possible to use any number of declarations at the same time. When this is done they must be separated using a semi colon e.g.

color:red ; font-size: 2em; text-align :center

Lists may be written on a single line or, as is often done, on separate lines thus

color : red ;
font-size : 2em ;
text-align : center ;

for this reason authors will normally add a semi colon at the end as well. This is optional but it tends to reduce the number of mistakes made when coding.

Note

Inline styles

The simplest way of applying styles uses the 'inline' method so we will look at it first. Please be aware that it is not a preferred method when others can be employed but it is permissible for occasional use.

Applying styles 'inline' is very simple using the html attribute 'style'. You just add a list of declarations as the value of the style attribute. For example:

<p style="color:red; font-size: large;">Text in a paragraph</p> and the result will be

Text in a paragraph

Using KompoZer to apply a style inline to some existing element

To apply a style

In Normal or Preview mode

  1. Click anywhere in the element.
  2. On the status bar look for the element marker e.g. <span> and click. The element becomes highlighted.
  3. Right click and select 'Inline styles'
  4. The 'Inline styles' window opens.
  5. Now by selecting one or more tabs in turn and making appropriate selections one or more style declarations may be added to the element

There are several reasons why inline styles are not recommended. This will become clearer later but may be briefly stated

This does not mean that inline styles should be prohibited. Occasional use is unobjectionable and is, in fact, the standard way of dealing with images, links etc.

Key to outlines and colours in use:

Property

Value

Declarations

Selector

Rule

STYLE RULES

Style rules collect one or more declarations together with a selector and provide a compact and powerful way to apply styles to a web page. Let's look at some examples:

.paraone
{
font-size
:
larger
;}
#footer
{
font-size
:
smaller
;
color
:
gray
}

Establishing rules and reusing them systematically helps to achieve consistency within and between the pages of a site.

CLASSES and IDs

The examples above show two different sorts of selector. The first, starting with a full stop (period) is a class selector. The second, starting with a hash (in US and Canada pound sign) sign, is an id selector.

The list of declarations is surrounded by curly brackets (braces) thus separating the selector from the first property.

Classes and ids allow styles to be applied to particular elements in a similar manner to that used by inline styles but the difference is that inline styles have to be repeated each time they are used classes and ids, having once been defined, may be re-used.

To apply a class or id to a html element use the corresponding attribute in the opening tag, for instance:

<p class="paraone">The first paragraph has bigger text</p>

The first paragraph has bigger text

<p id="footer">The footer appears less significant</p>

The footer appears less significant

Note that class name does not include the full stop and id name does not include the hash. These are used only for the selector.

Classes differ from ids. Classes may be re-used as often and wherever required. ids are unique identifiers which may be used once per page only. Typically they are used to define headers and footers, menus and main content areas of a page.

Defining rules using KompoZer

As we will see later style rules are stored in style sheets. KompoZer includes a CSS editor called CaScadeS which allows you to create stylesheets and define rules. Before you define a rule you must have a stylesheet but if you are working on a page which has none CaScadeS will create one for you.

To create a rule for a class or id

  1. Click the CaScadeS button on the Composition toolbar. The CSS Stylesheets window opens
  2. If the stylesheet in which you wish to create the class exists click it followed by the artist’s palette button . Else:
  3. Click the artist’s palette button. In the sheets and rules box you will see an internal stylesheet has been created for you
  4. To create a class click ‘Style applied to all elements of class’
  5. In the box you will see a full stop entered for you. Now either
    • Follow that by a name of your choice which must start with a letter or
    • Click the drop down arrow beside the box to get a list of already defined classes and click one of these
  6. Click ‘Create Style rule’
  7. You are now presented with a window headed ‘Selector’ followed by your class name. The window actually lists the style declarations for that rule, but of course that is now blank
  8. You can now add declarations to form a rule. To do this you click the tabs and make selections as appropriate. You can make selections from as many tabs as you wish. Details of these are covered later.
  9. If you click the 'General' tab you will see all the declarations for the rule. You can edit these here but it is better to leave the job to CaScadeS because if you make any errors the declaration will be deleted
  10. When you are satisfied click 'OK'

The same procedure may be used to set the style for an id. At step 4 click 'Style applied to element with specified id attribute' and at step 5 the box will contain a hash sign. The drop down box will provide a list of all ids used on the page.

Once created, rules may be edited by reopening CaScadeS, Click and expand the stylesheet and click the rule involved.

Applying rules using KompoZer

Using KompoZer, assuming that you already have defined the class required, to apply a class

  1. Click in the element
  2. On the format menu click the class drop down box
  3. Select the required class

Alternatively to apply a class or id

  1. Click in the element
  2. On the status bar (at the bottom of the window) click the marker for the element e.g. <p>
  3. Right click and select 'Class' or 'id' as required
  4. From the selection that pops up click the class or id which you want

ELEMENTS

A very powerful feature of CSS is the ability to specify an element name as selector.

Example:

ul
{
margin-left
:
5em
;}

This will inset all unordered lists (ul) using a left margin of 5em thus improving legibility of the page.

When an element name is used as the selector nothing else needs to be done. That style will be applied to all instances of the element (though other methods are available to override this is needed). The result is that the code on the page is minimised making for a very clean appearance.

Defining an element rule using KompoZer

Using KompoZer the method is essentially the same as defined previously.

To create a rule for an element

  1. Click the CaScadeS button on the Composition toolbar. The CSS Stylesheets window opens
  2. Click on the artist's palette button. In the sheets and rules box you will see an internal stylesheet has been created for you
  3. To create a rule for an element leave the default 'Style applied to all elements of type' selected
  4. You can use the drop down menu to select from several common elements, alternatively type the tag for the element (e.g. for a paragraph type p) in the box
  5. Click 'Create Style rule'
  6. Now proceed as described previously

Having shown the code for style rules you may still be wondering where they are recorded so that the page uses them. That is where stylesheets come in.

2 Stylesheets

A style sheet (commonly referred to as stylesheet) is just a list of rules. Let's take an example:

body   { margin: 15px 10px; background: white ; color: black; font-size: small; }
body   { font-family: Arial; }
p      { margin: 0.3em 0 0.3em 3em; padding: 0; }
ol, ul { margin: 0.3em 0 0.3em 6em; padding: 0; }

That's all there is to it. Usually, though not always, it consists of just ascii characters. Selectors and properties are case-insensitive as are most values but for some items such as font names and file names the case is significant.

The question is where does the sheet reside? There are two possibilities.

The preferred option is always an external stylesheet. This is because such a sheet can be used by several pages, or a complete site; should any error be found or a change required only one file has to be altered instead of having to trawl through all the pages to see what is needed.

An external stylesheet need contain nothing more than what is listed above. But comments are permitted and can be of assistance during maintenance. Here is an example:

/* Generated by CaScadeS */

Other than inserting the above as the first line of external stylesheets CaScadeS strips out all comments.

External stylesheets may be located anywhere which is accessible. It is usual to give them the extension .css It will probably confuse everybody if you don't.

LINKING EXTERNAL STYLE SHEETS

External stylesheets must be linked to every page involved. The linking information is included within the HEAD area in the page source code. The usual and simplest way is using the link method.

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

INTERNAL STYLE SHEET

Sometimes it is required to include the stylesheet information within the code for the page involved. This may be easier, for instance, during development.

Again the code is contained in the HEAD area using the 'style' element with the 'type' attribute. For example to include the above stylesheet the code would be.

<style type="text/css">
body { margin: 15px 10px; background: white ; color: black; font-size: small; }
body { font-family: Arial }
p    { margin: 0.3em 0 0.3em 3em; padding: 0; }
ol, ul { margin: 0.3em 0 0.3em 6em; padding: 0; }
</style>

MULTIPLE STYLE SHEETS

You can have as many stylesheets as you wish for any page. The choice is yours but you will find it easier to keep control if you limit this to just a few.

Again it is simpler to keep the style sheets together in the head of the page but any internal sheet(s) may be mixed with external ones.

Later we will consider the priorities involved if we have several stylesheets applied to one page.

Managing stylesheets using KompoZer

CaScadeS allows you to create, modify, delete and re-order both internal and external stylesheets and rules.

We will start by assuming that the page involved has no stylesheet either internal or linked.

To create an internal stylesheet

  1. Open CaScadeS
  2. Click the artist's palette . An internal stylesheet is created and will be listed in the 'Sheets and rules' box
  3. Create any rule. See above from step 3 if required
  4. When you have finished creating rules click 'OK'

You will now have an internal stylesheet correctly embedded in the head of your page.

Tip

When creating stylesheets, before you press the 'Export stylesheet …' button you will see a box headed 'Media List' and completed with 'all'. This shows that the style sheet is applicable to all media e.g. screen, print, braille, speech etc. It is possible to change this if required. But remember that if you disenfranchise some visitors you should provide an alternative stylesheet for them.

You can change the assignment at any time. Follow by pressing the 'OK' button.

To create an external stylesheet and link to it
(Exporting stylesheets)

  1. If no stylesheet exists
    1. Create an internal stylesheet as just described
    2. Create any style rules required
    3. Click the name of the stylesheet ('Internal Stylesheet')
  2. If there is an existing internal stylesheet CaScadeS and click the stylesheet
  3. Click 'Export stylesheet and switch to the exported version'
    A browse window will open so that you can choose where you want to store the stylesheet.
  4. Give it a name with the extension .css and click 'Save'.
    You will be returned to the 'sheets and rules' box and the filename of the stylesheet will replace 'Internal stylesheet'

Once you have a stylesheet, creating additional stylesheets is done in a slightly different way.

To create additional stylesheets

  1. Open CaScadeS
  2. Click the drop down box beside the artist's palette and select 'Internal stylesheet'.
  3. In the 'New Stylesheet' panel click 'Create Stylesheet'
  4. The created stylesheet will be highlighted in the 'Sheets and rules' box. Ensure that it remains highlighted so that any action affects this stylesheet and not in any other.
  5. You can now add rules or export the stylesheet as just described.

If you already have a stylesheet saved and wish to link to it.

To link to an external stylesheet

  1. Open CaScadeS
  2. Click the drop down arrow beside the artist's palette and select 'Linked stylesheet'
  3. Click 'Choose file'
  4. Browse to the required file and click 'Open'. You can make an entry in the 'Media list' box if desired (see Tip)
  5. Click 'Create stylesheet'

Reordering stylesheets

The order in which stylesheets appears in a file can be of importance. Data in stylesheets will be read in the order listed in the file. If there is no overlap in content the order is irrelevant but if, for instance, a print stylesheet is used to define styles for printing and is followed by an 'all' stylesheet the latter will overwrite the former if the same selectors occur in both which is likely.

To change the order, click the name of a stylesheet and use the up or down arrows above the sheets and rules box to change its position.

Deleting stylesheets

Click a stylesheet name and click the 'Remove' button above the sheets and rules box. When you delete an internal stylesheet everything is irrecoverably deleted. Deleting an external stylesheet only removes the link.

Editing rules

Rules may be amended as and when required by expanding the stylesheet and on the rule name. Then click the appropriate tab and make the settings required.

Note Changes to linked stylesheets are made immediately the 'OK' button is pressed. Click 'Cancel' to cancel changes. Changes to internal stylesheets are made when the page is saved.

Rules may be deleted using the remove button.

Selector names may be changed using the 'edit' button .

3 Setting up styles

By now you should be able to create internal and external, linked stylesheets. You should also be able to create rules for elements, classes and ids. What you are probably still missing is an understanding of what rules you should create, what properties to use in them and what values to use.

If you are using KompoZer your task will be greatly simplified. Otherwise HTML Dog has an excellent and clear reference listing all CSS2.1 properties along with the values which may be assigned. Linked pages give an explanation and examples of what can be done.

CaScadeS is organised so that when creating rules the properties are arranged on six separate tabs one each for

To a large extent the process of choosing then becomes self evident but a few notes may be helpful.

on setting up styles for text

FONT FAMILY

Beginners are strongly advised to use one of the predefined options

  • Arial, Helvetica, sans-serif
  • 'Times New Roman', Times, serif
  • 'Courier New', Courier, monospace

These provide alternatives of sans-serif, serif or monospaced fonts. In each case there are three values listed. The first is a font which may be relied on to be present on systems using MS Windows®, the second on Apple computers, the last is a generic type to be used if neither of the specified fonts is found. Font names must be spelled using the correct cases and names which include spaces should be enclosed in quotes.

  • If you wish to use any alternative fonts you should use the same structure with alternatives and finish with a generic type
  • Check on availability of the fonts you specify. Alan Wood provides a good resource on this. Check his General purpose fonts and which systems include them.

FONT SIZE

This may be set using several systems of units. For on screen use select from percentage, ems, exs or keywords (xx-small etc.). Most of the other units refer to print media. Never express font size in px. Sizes expressed as px will not scale on screen when text zoom is applied using Internet Explorer, this leads to serious user accessibility problems. You will find that 100%, 1em and medium usually result in the same size characters.

Colour

Colour may be set for text, borders and background. The properties involved are

Irrespective of whichever is involved the method of specifying is identical.

Colours may be described either by name or in R, G, B units, that is the proportion of Red, Green or Blue involved in the mix. (Some authoring tools may allow colour to be input using other systems of units — e.g. HSL, CMYK — but these will be changed into one of the systems recognised by CSS.)

CSS recognises 17 colour names:

Black

Gray

Maroon

Red

Orange

Yellow

Lime

Green

Teal

Olive

Aqua

Blue

Navy

Fuchsia

Purple

Silver

White

.

Text can be coloured orange by any of

The proportions of Red, Green and Blue are expressed as numbers in the range 0 to 255 either in decimal or hexadecimal using the structures shown in the example. The numbers are in the order Red, Green, Blue. When expressed as decimals the three numbers are separated by commas, when expressed in hexadecimal there is neither punctuation nor space between them.

Background

A background colour or image may be set for any element. When the image is larger than the element it will be cropped to size. Where it is smaller it is possible to specify the position and whether it is to be tiled. For example.

h2 { background-image: url(images/h2fill.png); background-repeat: repeat; }

By default images repeat (i.e. are tiled in both directions) so the second declaration above is redundant.

Tip
With XHTML pages background on the body does not extend into the margin. To apply a background here set the style for the html element.

When a background image is used it is recommended that a matching background colour should also be specified. If the image is not available, or while it is loading, the colour will show which improves the visitor experience.

The background covers the content, padding and border area of an element. The body element is an exception in that, for html pages, the background covers the margin area as well.

4 The CSS Box Model

CSS Box model The box model describes that way several css properties interrelate. Margin, border, padding and content can be considered as a set of nested boxes. The illustration shows the boxes with equal wall thickness all around. While this is the easiest way to set them up it is by no means necessary to do so and the labels show individual top, right, bottom and left properties which allow different values.

For most elements border and padding default to zero but many elements default to having a margin on top and bottom, others to left or right.

MARGINS and MARGIN COLLAPSE

If a bottom margin on an element is set to, say, 0.25em and a top margin on the following element to 0.5em then the gap between them will be the greater of the two NOT the sum. This is known as margin collapse.

For instance if the following rules were set:

h3 { margin-top: 0.5em; margin-bottom: 0.25em; }

p  { margin-top: 0.25em; margin-bottom: 0.25em; }

then the space between two paragraphs would be the greater if 0.25em and 0.25em i.e. 0.25em
and the space between a paragraph and a following h3 would be the greater of 0.25em and 0.5em i.e. 0.5em.

SHORTHAND CONVENTIONS

The components of the box model share several similarities. All have four components top, right, bottom, left and border has three sets of values.

Property Values
Margin Width
Border Width Colour Style
Padding Width

This leads to the possibility of having to set four declarations for margin:

similarly for padding while border may have twelve declarations. Several shorthand conventions assist here.

The property 'margin', border' or 'padding' used with a dimension as value will be interpreted as a width to be applied to all sides. e.g.

The clockwise convention allows different widths to be set for each side e.g.

will be interpreted such that the four values in turn apply to the width of the margin on top, right, bottom and left (running clockwise). Note there is no punctuation separating the values.

If two values only are given the first will apply to top and bottom, the second to left and right.

If three values are given the first applies to top, second to left and right, last to the bottom.

The convention applies in the same way to border and padding.

For border the same applies to colour and style. If one, two, three or four valid colour or style values are listed the same interpretation will be applied. Note that each declaration can have one to four values not twelve. With one exception width, colour and style must be specified separately. The exception is when the border on all four sides is to be the same then one length one colour and one style — on any order — will define the border. e.g.

border: 4px solid #ffa500;

For possible border styles consult HTML Dog.

The table above uses a combination of different border width, style and colours. Here is a set of declarations to do that:

border-style: solid dotted dashed double;
border-color: rgb(255, 204, 0) rgb(51, 204, 51);
border-width: 4px 10px 8px;

THREE DIMENSIONAL MODEL

Three dimensional box modelThe box model as described is two dimensional, flat model but it does have a third dimension which needs consideration.

Jon Hicks has provided an excellent descriptive diagram showing the layering of background, image and content and also the transparency of margin and padding.

Advanced readers will know that if the size of the content area is constrained and more material than will fit is inserted the material will overflow the 'content'. The diagram shows that in that case it will appear in front of the border and (invisible) padding and margin.

CONTENT SIZE

The content area is where the text in a paragraph, heading or table cell or where the image in an <img> element would go. Set a border on this of any required width and colour and space the border from the content by the padding. The whole structure is then spaced from adjacent material by the margin.

The size of the content area depends on the type of element involved and whether this uses the default setting or has been specifically set.

Default size

In the case of text items Headings, paragraphs and lists the width expands to the full width of any containing block, which may be the body or some other element. This width will then often vary as the visitor alters the viewport width. The height of such elements will similarly vary so as to accommodate the given material.

Other elements may behave differently, tables for instance default to shrinking their width so as to be just wide enough to hold the content. If the space available is reduced the table height will alter.

Set size

CSS Box modelThe CSS properties width and height set the size of the content area. Once set this will override any default and any change with viewport width will no longer occur. Generally avoid setting these properties unless they are essential.

Authors should differentiate between the content area and the actual content. In the default condition both will be the same but when the height or width is set using a style it is possible that the data in the area may be either smaller or larger than the space provided. In such cases the content will simply overflow the area, usually in the vertical direction.

Overflow

Overflow can be controlled using the 'Overflow' property. In CaScadeS overflow appears on the box tab and allows four different values:

CENTRING

Text may be centred using the declaration text-align: center; but this aligns the text within the content area, it does not align the content area. An example of text centred in a paragraph:

Centred text

uses the style border: 1px solid rgb(66, 137, 181); text-align: center;

The paragraph, like all paragraphs on this page, has a left margin of 3em. That moves the content box away from the left edge, indicated by the orange border. The text is centred in the content box but the content box is not centred.

An example centring the content area is:

Centred text

This uses the style border: 1px solid rgb(66, 137, 181); text-align: center; width: 6em; margin-left: auto; margin-right: auto;

That will take some unbundling. The border has been left as previously. The width of the paragraph has now been specifically set. Left and right margins have been set to auto. When this is done on any element whose width is known will be centred. The content box is now centred between the orange borders and the text is centred in the box.

This usually means that the width must be specifically set but in the case of tables, provided that they do not occupy the full available width this is not required.

Of course what width do you need to set for the text? Since the visitor may zoom the text this seems unknowable. The technique is to use the 'em' unit. This is, notionally at least, the width of the letter 'm'. As the visitor zooms the text this width will alter so the allocated space changes. To find the best value just experiment.

5 Links

PSEUDO CLASSES

Links are based on the anchor <a> element. This has several states which are styled using pseudo-classes e.g.:

These classes are automatically applied to 'a' element without any author action and are acted on according to the state or history of the element.

The rules are set using the selectors:

Make it clear
what is a link
what is not

By default text links are rendered coloured and underlined and after visiting the colour may change.

In styling links one principle is important

This is typically achieved by retaining the convention of underlining links and not underlining other text and also by introducing some change when a link is hovered over (to reassure visitors) e.g.removing the underlining, changing the colour or adding a border. The browser will also normally change the cursor when you hover over a link.

An example of a set of rules might be

a:link    { color: blue; text-decoration: underline; }
a:visited { color: purple; }
a:hover   { text-decoration: none; }

If you do not want to differentiate links which have been visited you may need to override the browser default by setting the same declaration for the :link and :visited states. e.g.

a:link, a:visited { color: blue; text-decoration: underline; }

One thing that is important is to ensure that the a:hover rule is the last otherwise the others will override it.

6 Block and inline

Block elements

Paragraphs, titles, lists, tables etc are block items.

Each time you start a new such item …

It starts on a new line.

The background makes it clear where the content area of these blocks are.

Understand the difference

Inline elements are not the same as inline styles.

Inline elements are specific elements which display inline with other material

Inline styles may be applied to any element using the style attribute.

Inline elements

Some elements like strong, which was used here to make the type heavier, do not start new lines and are referred to as inline elements. The code used would be like
<p>Some elements like <strong>strong</strong>, which was used here

Images are a very common example of inline elements. e.g.
<p>Images <img style="width: 30px; height: 15px;" src="images/flag_united_kingdom.png" alt=""> are a very common example

A special case of an inline element, which we will now meet, is the 'span' element .

<div> and <span>

It is possible that you may not have met these elements before. This is not surprising because by themselves they do nothing. They are provided simply so that you can add an attribute to them. Remember that any element may be allocated a style, class or id.

For example, by adding a span and allocating it a style, I can make this text purple.

Use code like <span style="color: purple;">purple</span> in the paragraph. Span is used where there is no inline element available to provide the formatting required.

Using inline elements with KompoZer

Several inline elements will be created automatically in KompoZer when the corresponding menu selection or Format bar button is used. As an example when you use the menu selection Format > Text Style > Code the text will be enclosed within <code>…</code> tags.

You can modify the appearance of such an element by clicking its marker on the status bar and applying a class or an inline style.

Creating and using a span

Creating a span allows you to apply a customised style to a section of text. KompoZer cannot create an un-styled span directly but you can get around this easily. Several buttons on the format menu achieve their end by creating a span and applying a style. As an example:

To set a section of text (not a complete paragraph) in upper case

  1. Select the text
  2. Click the 'Bold' button . This creates a span and applies the style font-weight: bold;
  3. On the status bar click the <span> marker
  4. Right-click and select 'Inline styles'
  5. In the general tab that opens delete the style text. This deletes the style but retains the span marker.
  6. Go to the 'Text' tab
  7. In the case box select 'Upper case'

It is possible to apply any other style in the same way by selecting the corresponding tab and making the required selections.

div

The div element marks a division of a page. It is actually one of the most powerful and useful elements available for use in page layout. This will become clearer later when we consider positioning.

Recall the structure you used in the first demonstration

<div>
is a
block item
which can
contain other blocks

This allowed a single paragraph to be given a border and margins. What if we wanted several paragraphs, some lists and a few images to share the same sort of outline? If we apply the same class to each, at best we will get gaps between them and top and bottom borders for each. But what if we want them all to share the same borders, and perhaps background as well?

The answer is not at apply the class to the individual items but to enclose all of them in a division and to apply the class to that instead.

<div class="styled_with_border">

In the div we then include whatever we want along the lines

<div class="styled_with_border">
<p>Paragraph1 content</p>
<ul>
<li>List item</li>
<li>List item</li>
</ul>
<p>Paragraph2 content</p>

</div>

The result, after substituting some fake Latin into the text would be something like:

Creating and using the <div> element with KompoZer

There are various ways of creating divs using KompoZer.

To create a blank div

  1. Place the cursor on a blank pace on the page i.e. not in a text item. If necessary hit the 'enter' key to create a new blank paragraph
    Note Do not try to create a div as the last item on a page unless you do not need to add items after it
    Note It may be easier to see what is happening in HTML tags view with View > Block outline selected
  2. Click the first drop-down box on the format toolbar
  3. Click the last option at the bottom of the list - Generic container (div)
  4. The div is created formatted as body text. KompoZer will, in normal view, show the outline of the div dotted red

To create div enclosing existing items

  1. Select the items to be enclosed
  2. Click the Borders button. This button is not installed by default. Customise your toolbar if necessary
  3. The Borders window opens. Make no selections just click 'OK'
  4. The div is created. KompoZer will, in normal view, show the outline of the div dotted red

Note The Borders button is intended to create an inline style to set a border around an element. Because you have set no properties the style will be blank i.e. the code will be <div style="">. This is an error. To correct it right-click the marker for the div on the status bar and click 'Inline styles'. The window that opens will be empty. Click 'OK' and the style will be removed.

To set styles for a div

Setting styles for a div is no different from any other element.

  1. Click anywhere in the div
  2. On the status bar click the <div> marker. For most elements this marker is that furthest to the right. Because a div may contain many other elements you may have to search to the left until you find the corresponding marker. Click the marker. All the content of the div will be highlighted. If you have clicked the wrong marker try another
  3. Right-click and now apply a class or id or set an inline style as appropriate

Characteristics of div

To examine the characteristics of the div element I'll set one up with a background and border to make it easy to see. I'll use an inline style with the code

<div style="border-style: solid; border-color: #4289b5; border-width: 2px 4px 4px 2px; background-color: #f4f8ff;"><p>Text …</p></div>

Text in a paragraph within the division.

As you see it stretches all the way across — unlike the paragraphs we looked at before it has no left margin — It appears after the previous block and can hold some text.

Next let's add to the inline style so as to set the width of the div. width: 150px;

Text in a paragraph within the division.

Two things occur

Of course now that I have control of the width I could centre the div by setting margin-left: auto; margin-right: auto; You will remember that to center something in this way you must first specify the width.

Text in a paragraph within the division.

I need a div that I can reuse later so I'll just set up a class so that I can use that.

.outlined_div {

border-style: solid; border-color: #4289b5; border-width: 2px 4px 4px 2px;
width: 50px; height: 50px;
background-color: #f4f8ff; }

I'll save that in my stylesheet then insert it into my file when I need it using the code:

<div class="outlined_div"></div>

And this is the result.

Recap

Let's just summarise what we know about divisions

That's really all there is to know about them.

I'll be reusing the div quite a bit in the next section. There is no special reason for that, in many cases I could use almost any element, often I want an element that can hold explanatory text hence the div is chosen.

7 Positioning

Normal flow

Normal flow
Order of code

order on screen

Look back at section 6 for instance at the code used to demonstrate how to use a div. Compare with the image on the screen (or your own trial). You will note that the order in which items appear on the screen is the same order as that in which they appear in the code.

That is Normal flow — the order of the code is the same as the order in which it is displayed on screen.

The next concept to be introduced is that of 'Float'. In discussing this I need two icons.

Will show the position of the code for an element that has been 'Floated to the left'.

Will show the position of the code for an element that has been 'Floated to the right'.

Float

Float is one way of moving the position of an element from where you might expect to find it. For the demonstration I will be using the outlined div preciously prepared and I will put some explanatory text in the div to help.

Floated right

I want to use a div because it is a block item. Because this text is in a paragraph and because a paragraph (or any text block) cannot hold another block item I have inserted the div just before the paragraph just where the yellow icon appears. Normally that would mean that it was displayed between this paragraph and the previous, whereas in fact it is to the right of this paragraph. This has been achieved by applying the inline style style="float: right;"

Floated right
Floated left

The result of this is that the div moves to the edge of the space available and the text wraps around it. I could just as easily have floated it to the left as here.

Notice that:
a - Not only does the block before which the item was floated wrap but all following ones do as well until the wrapping is no longer needed.

b - The floated items do not necessarily appear on screen in the same sequence as in the source code.

Floated left with margin

c - Items floated left and those floated right do not interfere with each other.

d - Text wraps around floated items but can just touch them which is quite ugly. You can add a small margin to improve the appearance if this happens.

BUT, BUT, BUT … you may be thinking. The box is created by applying a class to a div but I just said that float was achieved by applying a style.

There is no problem, actually you can apply a style and, if you need, several classes to any element. The code for the last dem is

<div style="float: left; margin-right: 4px;" class="outlined_div">Floated left with margin</div>
Moving on.

What floating does is move an item to the right or left as far as possible until it meets a barrier. So let's try floating several items. Soon after each other. I'll number each in the order in which it occurs in the code.

1
2
3
4
5
6
7
8
9

The first div floats to the right limit but the next floats till it meets the first. Others behave similarly. If your screen width is more than 800 px wide narrow your viewport and check the result.

This is quite a nice way of displaying many small items even when they are of fixed size but the dimensions of the visitor's screen are unknown. Look back at the section on Colour to see an example.

1
2
3
4
5
6
7
8
9

What this means is that while right floated and left floated elements do not interfere with each other elements floated to the same side may. Of course there are times when this could be quite irritating. You would really prefer the divs to appear one below the other.

This is simply achieved by adding the declaration clear: right;

The example at the right shows the result. Of course the divs now touch each other. To avoid this simply add a small top or bottom margin to each.

Let's summarise the relevant style properties and values:

Property Possible Values
Float Left Right None
Clear Left Right Both None

I've finished that topic but the accompanying diagrams are still running down the page and this text is wrapping to the left. It's quite difficult to start a new subject under these conditions but here's how.

In the next title or paragraph, or whatever, set clear right; or clear: both;

Floated elements
are removed from
normal flow

Setting 'clear: right;' ensures that the next item, whether floated or not, will appear below anything previously floated right. Similarly for left'. Setting 'clear: both;' ensures that it will; appear below anything previously floated.

This problem is much more acute on web pages than in desk top publishing or any paper publishing system. That is because on paper you know exactly where things are and so can manipulate items to make an attractive layout. On a web page the layout will depend on many factors outside of the author's control so you may have to put up with white space where you really would prefer not to have it.

Recap

Floated items are taken out of the normal flow.

Using KompoZer to set up floats

Open Cascades in any of the usual ways. All the properties involved in setting up floats will be found on the 'Box' tab.

In the example shown a style named 'right' has been defined and for it the following properties are being set.

  • Float – set to 'right'
  • Clear – set to 'right'
  • Margin left – set to '4px'.

On this page many figures use this style. Setting clear to right means that they will stack one below the previous even if inserted in the text before there is really space for the figure.

Setting margin left to 4px means that any adjacent text will keep clear of the image rather than touch it.

Absolute and relative position

Absolute position

Absolutely positioned elements
are removed from
normal flow

The style property position : absolute; is a very powerful tool for use when positioning elements on a web page. Like float it removes elements from the normal flow and does so with a vengeance. Float is limited to moving things to the right or left (though if you apply top or bottom margin you have some control of vertical position also) and they never overlap. Absolute position acknowledges no such restriction and can make things appear anywhere on (or off) the page.

To apply absolute position apply the code

selector { position: absolute; top: value; left: value; }

The properties 'top' and 'left' are known as offsets and alternatives are 'right' and 'bottom'. Substitute the required selector and numbers for 'value'.

The first question is from where are the values measured?

Every positioned element is positioned within some other element which is referred to as its 'containing block’.

Offsets are measured from the ‘padding edge'’ of the containing block (i.e. from the outer edge of any padding on the containing block) to the outer margin of the element being positioned.

What is the containing block?

I'm sorry, this is where it starts to get difficult but once you are through the woods you will see your way.

If you start a new simple page with little in it and position something using position: absolute; it will be positioned with respect to the viewport on the screen. If you are new to this I suggest you try it. You can set up a div or use an image or even a paragraph. Then give it an inline style like

style="position: absolute; top: 100px; left: 200px;"

Repeat with a copy but change the values slightly. You will see that there is no difficulty in getting things to overlap.

You could then change some of the offsets from 'left' to 'right'.

Using KompoZer to set up absolute positions

Open Cascades in any of the usual ways. All the properties involved in setting absolute position will be found on the 'Box' tab.

In the example shown the style is being set up inline so no 'sheets and rules' pane shows.

A style has been defined and for it the following properties are being set.

  • Position – 'absolute'
  • Offset top – '200px'
  • Offset left – '100px'
  • Width – '120px'
  • Height – '50px'

By now you will see that the positions are being set from the edges of your viewport — so the containing block is the viewport. Positioning is being carried out with respect to the viewport.

Add more text to your page so that there is sufficient to allow the page to scroll. Change some instance of 'top' to 'bottom'.

Now scroll the page. 'Left' and 'right' are still being interpreted with respect to the viewport but 'top' and 'bottom' are scrolling.

In fact all four offsets are interpreted with respect to the initial position of the viewport (before scrolling).

Absolute positioning is first carried out with respect to the initial containing block which, before scrolling, is the viewport.

Once you have scrolled the page the current viewport moves down the page but the initial containing block remains at the top of the page. Positioning is no longer with respect to the viewport. The figure on the right represents this situation.

It is of course still possible to set positions of elements by counting down from the top of the page but this is not always satisfactory.

If you are using a 'fluid design', that is one which does not constrain the page width but allows it to vary as the visitor changes the viewport width, items on the page will move up or down the screen and there will no longer be any correspondence between the item and any measurement in pixels or in fact any other measuring system.

If you then want to position something using Absolute positioning some way of re-basing the measuring point is needed.

Call in position: relative;

Relative position

In contrast to elements with position absolute those with position relative remain in normal flow. That means that I can place something in normal flow, allocate it a style with position: relative; top:0; left:0; and it will stay where it was. In fact I don't even have to allocate any offsets at all.

A division is particularly convenient for this because it can hold other elements. Once I have set up a division with position:relative it can act as a containing block for other elements. Let's take an example of that now.

Relatively positioned elements
remain in
normal flow

I have taken the styled div used previously and given it the opening tag

<div style="width: auto; position: relative; height: auto;" class="outlined_div">

By setting the width to 'auto' I have removed the width constraint embedded in the class (check back) so the div occupies full width of its container. Note that the inline style overrides the class.

So what I have is a division with position relative in which I can insert code in normal flow like these paragraphs and also floated items like the display box but which in addition could act as a containing block for something that I might like to position.

Let's set up an absolutely positioned in this. I'll use a second copy of the outlined div just before this paragraph using the code
<div style="position: absolute; margin-left: 38px; left: -128px; top: 0px;"
class="outlined_div"></div>

Because the inserted div is absolutely positioned it is removed from normal flow and doesn't appear inline with other items. where is it?

It is positioned with respect to its containing div (this div) and since the value of top is 0px, its top lines up with the top of this div. The left offset is negative so it appears to the left of this div, in fact in the menu area. Clearly it is linked to this div because it scrolls with it.

Containing blocks

Only positioned elements
form containing blocks

So what can act as a containing block.?

A block may hold positioned and non positioned elements but only those that are positioned act as containing blocks. It follows that

You will find that most commonly divisions are used when we need to create a containing block for positioning. This is convenient because divisions can hold other block items. However any element may act as a containing block and text blocks like paragraphs are quite suitable for positioning inline items like images.

What then is positioned?

This is easy. To be considered 'positioned' an element must be allocated the property 'position' with one of the values 'absolute', relative' or 'fixed'. We won't be considering elements with position fixed in this introduction

Note that floated elements are not considered positioned.

My page on absolute positioning covers this subject in more detail, includes many examples and discusses browser bugs which may be encountered.

The body

You may have noticed that the body element has no part in the positioning regime. It is the nested positioned elements which take part rather than those in the code sequence.

Nevertheless it is sometimes convenient to position with respect to the body. It should be unnecessary at this stage to tell the reader how to achieve this. Style it with position: relative; If your page design uses a fixed width and is of no great length this may be a convenient way of laying out elements on it.


8 Priorities

By this I refer to the issue of what wins over others if I have several stylesheets, rules and the like? Beginners sometimes agonise over this but it is rarely an issue until a site becomes complex.

I will deal only with a few simple cases.

Beginners should try to specify things once only. For example if you have declared a rule:

p { color : red; } you should avoid declaring a rule

p { color : green; }

Often if different browsers render a page differently it is because their default style sheets differ. If the author has specified the required style this should not occur and it is likely that he or she has overlooked specifying or preferred not to specify a style for some element.

There are other more detailed (and complex) rules which generally will not concern the beginner.

9 Glossary

ascii
American Standard Code for Information Interchange. Defines a set of 128 characters including numbers, upper and lower case non accented letters plus punctuation and 33 symbols. This makes 95 printable characters as well as a number of control characters many of which are now obsolete. This must not be confused with ANSI which does not define a character set though often misquoted as doing so.
Attribute
A property of an element which alters its behaviour or appearance.
Block element
An element which always creates a new line (break) when used.
Border
A (coloured) line that may be displayed visually around an html element.
Class
A label that may be applied to an element to control the rendering. Classes may be reused.
Component
Used in this document to include html elements and elements qualified by the application of a class or id.
Content
The area of any element inside any margin, border and/or padding.
Declaration
See Style basics
Element
The basic building block of an html page e.g. paragraph, list, image.
Fluid design
A page layout in which the width of the body is not fixed so that it may accommodate to varying width of the viewport.
id
A label that may be applied to an element. It can may be used to control the rendering or for other purposes. ids may be applied once only.
Inline element
An element which instead of creating a new line site in line with other content.
Inline style
A style expressed using the style attribute of the element to which it applies.
Margin
A transparent space surrounding any border of an element which typically controls the distance to adjacent elements.
Padding
Transparent space between the content of an element and any border.
Property
See Style basics
Rule
Defines the rendering of components on a web page. Included selectors and declarations. See Style rules
Stylesheet
A text file which includes rules defining the rendering of components on a web page. It may also include comments.
Selector
A string which controls the linkage of a rule with components of a web page.
W3C
Worldwide Web Consortium.

10 References

The definitive specifications

Tutorials

Other resources

  • htmldog A good resource listing all CSS2.1 properties and possible values which may be assigned
  • CSS validator a service from W3C which allows you to test your stylesheets for validity

More detailed resources

These generally go far beyond the scope of the present document but may be of interest to those needing to go deeper.

  • Web Devout David Hammond lists support (or lack of) for CSS properties for four modern browsers.
  • Microsoft http://msdn.microsoft.com/workshop/author/css/reference/ attributes.asp publish a list of which CSS properties are supported by various versions of their browsers.
  • Microsoft http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnie60/html/cssenhancements.asp provide information on Internet Explorer 6 support for CSS.
  • W3C http://www.w3.org/Style/CSS/Test/ have a test suite for your browsers.
  • Matthias Gutfeldt http://gutfeldt.ch/matthias/articles/doctypeswitch/table.html Details of how to select quirks or standards mode in a number of older browsers.
  • Box model problem with MSIE http://www.communitymx.com/content/article.cfm?page=1&cid=E0989953B6F20B41 is discussed by John Gallant and Holly Bergevin.

Absolute Positioning

Floats

Collapsing margins

  • Eric Meyer http://css.maxdesign.com.au/floatutorial/ covers this and many other CSS issues.
  • Minz Meyer http://www.researchkitchen.de/blog/archives/css-autoheight-and-margincollapsing.php covers the same topic.
  • Andy Budd http://www.andybudd.com/archives/2003/11/no_margin_for_error/ considers the interaction between collapsing margins and cleared floats.

Captions

  • Jukka Korpela http://www.cs.tut.fi/~jkorpela/www/captions.htmlon Image captions on web pages.