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.
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.
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.
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
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
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:
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
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>
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:redfont-size:2emtext-align:centerThe 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
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
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 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:
Establishing rules and reusing them systematically helps to achieve consistency within and between the pages of a site.
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.
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

Click
the CaScadeS
button on the Composition toolbar. The
CSS Stylesheets window opens
. Else: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.
Using KompoZer, assuming that you already have defined the class required, to apply a class
Alternatively to apply a class or id
A very powerful feature of CSS is the ability to specify an element name as selector.
Example:
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
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.
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.
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">
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
. An internal
stylesheet is
created and will be listed in the 'Sheets and rules' boxYou 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)
Once you have a stylesheet, creating additional stylesheets is done in a slightly different way.
To create additional stylesheets
If you already have a stylesheet saved and wish to link to it.
To link to an external 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
.
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.
FONT FAMILY
Beginners are strongly advised to use one of the predefined options
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.
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 may be set for text, borders and background. The properties involved are
color applies
to textborder-color applies
to bordersbackground-color applies to
backgroundIrrespective 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
color : orange ;color : rgb(255, 165, 0);color : #ffa500 ;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.
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.
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.
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:
margin-width-topmargin-width-rightmargin-width-bottommargin-width-leftsimilarly 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.
margin; 2em; will provide the same
margin on
all sidesThe clockwise convention allows different widths to be set for each side e.g.
margin: 0.25em 0 0.25em 3em;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;
The
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.
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
The
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 can be controlled using the 'Overflow' property. In CaScadeS overflow appears on the box tab and allows four different values:
Overflow: visible;This is the
usual
default condition when overflow is not specified. The content will
overflow the content area if requiredOverflow: hidden; The content will
be clipped at the limits of the content areaOverflow: scroll; Scroll
bars appear on both axes allowing any overflowing
content to be brought into viewOverflow: auto; As for scroll but
the scroll bar(s) appear only when required 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.
Links are based on the anchor <a> element. This has several states which are styled using pseudo-classes e.g.:
:link the
initial state of a new link:visited a
link
that has been visited:hover a
link over which the cursor is hoveringThese 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:
a:linka:visiteda:hoverMake 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.
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.
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 .
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
Select
the text
. This creates
a
span and applies the style font-weight: bold;It is possible to apply any other style in the same way by selecting the corresponding tab and making the required selections.
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
To create div enclosing existing items
This
button is not installed by
default. Customise your toolbar if necessaryNote 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.
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.
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.
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 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.
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;"
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.
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.








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.








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.
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.
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.
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.
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;
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.
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.
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.
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.
p.capitals { text-transform : uppercase; }
or
.capitals { text-transform : uppercase; } will prevail over
p { text-transform : none; } irrespective of the order
encountered.There are other more detailed (and complex) rules which generally will not concern the beginner.
The definitive specifications
Tutorials
Other resources
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.
Absolute Positioning
Floats
Collapsing margins
Captions