Wednesday 20th of August 2008 08:15:33 PM

CSS Tutorials > CSS Positioning

CSS Positioning

In this tutorial we show you how to position images, text, and other elements on your page using CSS. If you've been building web pages for some time, it's likely that you use HTML tables for laying out your pages. This used to be the only way to control the position of elements on the page. However, CSS2 (CSS level 2, the latest version of CSS at the time of writing) provides new ways to control positioning. CSS gives you control down to the pixel level, and it can also do some things which were harder or impossible to do with tables.

For example, the coloured blocks below are all positioned using CSS:

Sage

Oh the moon, the moon.

Try doing that using tables! ;-)

Accessibility

One of the great advantages of using CSS for layout is that it is fully standards compliant. This means that your site will be much more accessible for people using alternative browsing methods such as handheld devices, braille browsers, or text only browsers.

These users will appreciate being able to get at the content of your Web pages without having to wade through layers of presentation tables, and in fact will have a similar view to those using older browsers that don't support CSS2. Users with older browsers will still be able to read your pages, but will not see all the fancy formatting you've applied.

Because of this, it's a good idea to place the items that you want to appear at the top of the page at the top of the HTML code, and so on through to the bottom of the page. This way, older browsers will display your page content in the correct order.

Older Browsers

The techniques used in this tutorial will work in Internet Explorer 5+ and Netscape 6+ (around 93% of Web users according to recent statistics).

Internet Explorer 4 and Netscape 4 provide partial support for CSS2. Some techniques will display correctly in these browsers while others will not. For example, Netscape 4 fails to display the background-color of a div tag.

Now let's take a look at how to position stuff with CSS!

Containers

The block example near the top of this tutorial uses three containers which are positioned using CSS. Containers can contain other HTML elements such as images, text, tables, and so on. In the example above, two of the containers hold text, while the other one is empty. Generally we use the HTML tag <div> to specify containers, and we use id's to refer to each container within our stylesheet.

Example:

<div id="mydiv">
This text is large and bold and uses small capitals.
</div>

We can then apply styles to our container by using the # selector in our stylesheet:

#mydiv {font-variant: small-caps;
font-size: 1.5em; font-weight: bold}

to produce something like this:

This text is large and bold and uses small capitals.

Positioning

The position property is used to determine what kind of positioning we want to use for the container. The most useful values are:

Value

Example

absolute

{ position: absolute }

relative

{ position: relative }

Absolute positioning is the easiest to understand, so we'll start with that!

Absolute Positioning

Absolute positioning allows us to remove a container from the context of the other elements around it and position it wherever we want on the page. We tell the browser exactly where we want the container to appear using the top, left, right, and/or bottom properties.

The top property defines how far from the top of the page we want the top of our container to appear. If we use a positive value, then our container is moved down from the top of the page, whereas a negative value would move our container up from the top of the page.

The left property defines how far from the left edge of the page we want the left edge of our container to appear.

The right property defines how far from the right edge of the page we want the right edge of our container to appear.

The bottom property defines how far from the bottom edge of the page we want the bottom edge of our container to appear.

In all cases, if we don't want to offset the container in a particular direction, we can just leave the property out of our stylesheet.

The allowed values for top, left, right, and bottom are:

Value

Example

length

{ top: 0px }

percentage

{ left: 10% }

length values are specified using the CSS length units such as px, em, and cm. For a full description of these, see the tutorial CSS Units.

percentage values are relative to the parent element's dimensions. In our next two examples this would be the entire Web page.

Examples

Our first example uses the bottom and right properties to absolutely position a copyright notice on a Web page, as shown below:

© ELATED 2003

To do this, we define a container called copy to hold our copyright notice:

<div id="copy">
&copy; ELATED 2003
<div>

We then position it in the bottom-right corner using CSS:

#copy { position: absolute; right: 10px; bottom: 10px; }

(Remember that we use the # in a stylesheet to refer to an element which has been given an id.)



For our second example, imagine that you want to build a page that looks like the one below:

header image
home | diary | photo gallery | contact

Welcome

to my site...

You would split the page into three containers - header, menu, and content:

<div id="header">
<img src="header_image.jpg"
width="100%" height="50" alt="header image">
</div>
<div id="menu">
home | diary | photo gallery | contact
</div>
<div id="content">
<h1>Welcome</h1>
<p>to my site...</p>
</div>

The stylesheet would position them one underneath the other using CSS code like this:

#header { position: absolute; top: 0px; left: 0px; }
#menu { position: absolute; top: 50px; left: 0px;
width: 100%; height: 10px;
background-color: #333366; color: #FFFFFF"}
#content { position: absolute; top: 65px; left: 0px;
width: 100%; background-color: #FFFFFF;
color: #000000"}


Relative Positioning

With relative positioning the container is positioned relative to its usual position on the page.

As with the absolutely positioned containers, we can use the left, right, top, and bottom properties to modify the position. However, these modifiers work in a slightly different way with relative positioning. The main things to remember are:

  • We always measure from its usual position on the page. (Absolute positioning measures from the top-left of the page.)

  • We always offset the top-left of the container. (Absolute positioning offsets different edges depending on which property you're using to offset the container.)

The top property defines how far from the top of its usual position we want the top of our container to appear. If we use a positive value, then our container is moved down from the usual position, whereas a negative value would move our container up from the usual position.

The left property defines how far from its usual position we want the left of our container to appear. Positive values will move the container right, and negative values will move it left.

The right property defines how far from its usual position we want the left hand edge of our container to appear (not the right hand edge, as you might expect!). Setting right: -5px is the same as setting left: 5px with relative positioning.

Similarly, the bottom property defines how far from the usual position we want the top of the container to appear. Setting bottom: 50px is the same as setting top: -50px when using relative positioning.

The examples below use cross-hairs to show what would be the normal position of the container on the page. This is the point that the left, right, top, and bottom properties are measured from. We've also given the containers a background colour, so that you can see more easily how they're offset from their top-left corner.

Examples

#mydiv { position: relative; top: 0px; left: 0px; }
This text is positioned where it would usually appear on the page. Notice that the top-left corner is at the centre of the cross-hairs.


#mydiv { position: relative; top: 0px; left: 50px }
This text is positioned 50 pixels right of where it would usually appear.


#mydiv { position: relative; top: 5px; }
This text is positioned 5 pixels below where it would usually appear.


#mydiv { position: relative; bottom: 5px; right: 10px; }
This text is positioned 5 pixels above and 10 pixels to the left of where it would usually appear. (Remember that we're offsetting the top-left corner of our container.)


Absolute Isn't Always Absolute!

When explaining absolute positioning above, we assumed the containers are being positioned absolutely within the entire Web page. In fact, absolute positioning is a little more complex, and containers can actually be positioned absolutely within another container that has been positioned on the page.

Our absolutely positioned examples above actually make use of this advanced positioning concept, in order to show you the examples inline, instead of using a new HTML page for each example! To do this, we absolutely positioned our example containers within relatively positioned containers. This has the effect we want because:

  1. The relatively positioned element will appear at the appropriate position in the document (i.e. within the document flow).

  2. With absolute positioning the browser doesn't reserve space within the document flow for the container. This means that if you wanted to mix absolutely positioned items with some normal text on the page, one would overlap and obscure the other - not much use for our examples!

  3. On the other hand, relatively positioned containers work much more like the HTML elements you're used to, in that they do take up space within the document flow.

In the example below, the relatively positioned element appears within the document flow as well as taking up the space needed to display it, so we end up with absolutely positioned elements shown inline.

#container {position: relative; width: 100%; height: 125px;}
#copy {position: absolute; right: 10px; bottom: 10px;}
<div id="container">
<div id="copy">
&copy; ELATED 2003
<div>
<div>
© ELATED 2003


Controlling the Size of a Container

You should now know how to position your containers on the page. Now we'll explain how you can control the size of your containers.

The width and height propertes are used to determine how large a container is. These are specified using the CSS length units such as px, em, and %. For a full description of these, see the tutorial CSS Units.

Examples:

#mydiv1 { width: 250px; height: 50px; }
This container is 250px wide and 50px high. It has a background colour so that you can see the dimensions.
#mydiv1 { width: 75%; height: 50px; }
This container is 75% wide and 50px high. When using percentage units, the dimensions are calculated as a percentage of the parent element - in this case a <td>.

Additionally the overflow property can be used to determine what happens when the container is filled to over-flowing. The allowed values are:

Value

Example

auto

{ overflow: auto }

hidden

{ overflow: hidden }

visible

{ overflow: visible }

scroll

{ overflow: scroll }

auto will automatically display scrollbars if the content overflows the container.

hidden will clip the element and hide any content which overflows the container.

visible will display all content, including any that overflows the container.

scroll will always display scrollbars within the container.

Examples:

#mydiv1 {position: absolute; left: 25%; width: 50%;
height: 50px; overflow: auto}
mydiv1's overflow property is set to auto. A scrollbar will be displayed only if there is too much text to display. This example should show a scrollbar. Try it out - scroll down to see all the text.


#mydiv2 {position: absolute; left: 25%; width: 50%;
height: 50px; overflow: hidden}
mydiv2's overflow property is set to hidden. When there is too much text to display the content is clipped and the overflowing text is not displayed. Try to see the text at the bottom of this container!


#mydiv3 {position: absolute; left: 25%;
width: 50%; height: 50px; overflow: visible}
mydiv3's overflow property is set to visible. When these containers have too much text to display, it will be displayed anyway. This example text should overflow the area that has been allocated to it.


#mydiv4 {position: absolute; left: 25%;
width: 50%; height: 50px; overflow: scroll}
mydiv4's overflow property is set to scroll. The scrollbars are always visible, whether the content overflows or not!


Layering Up

When displaying containers that overlap, you might sometimes want to specify which container lies on top of another. The property z-index allows us to do this. The allowed values are:

Value

Example

auto

{ z-index: auto }

integer

{ z-index: 2 }

auto will use the same stacking level as the parent element.

integer defines the stacking level of the element. An element with a higher stacking level will be displayed on top of one with a lower stacking level. Negative integers may also be specified.

Examples:

#mydiv1 {z-index: 1}
#mydiv2 {z-index: 2}
I'm underneath!
I'm on top because I have a higher z-index

The End

That's the end of this tutorial. We hope you found it useful. If you're still stuck and would like further help, check out our online Help Forums, where you can get assistance from members of my and other webmasters.

If you would like to offer us feedback on this or any of the tutorials, please contact us. Have fun!


The drawback with border is that you can onlydefine "global" styles, widths, and colors. In otherwords, the values you supply for border will applyto all four sides equally. If you want the borders to be differentfor a single element, you'll need to use some of the otherborder properties. Of course, it's possible to turn thecascade to your advantage:

H1 {border: thick silver solid;border-left-width: 20px;}
Figure 11-17

Figure 11-17. A comparison

Furthermore, if we view the web page using a browser without stylesheets, it will come out looking like Figure 11-18.It may not be as pretty, but it's still quite readable.

Figure 11-18

Figure 11-18. The styled page without any styles

11.1.3.1. Cleaning up

There are a few places where the CSS version isn't quite thesame as the printed version, as a detailed study of Figure 11-17 reveals, and of course the creation of the

The classes that import and export information from your ApplicationML file must use the parser and SAX or DOM API in order to import the information. These classes can access this information by using one of the following strategies:

  1. Use DOM to directly manipulate the information stored in the document (which DOM turns into a tree of nodes). This document object is created by the DOM XML parser after it reads in the XML document. This option leads to messy and hard-to-understand code. Also, this works better for document-type data rather than just computer generated data (like data structures and objects used in your code).
  2. Create your own Java object model that imports information from the XML document by using either SAX or DOM. This kind of object model only uses SAX or DOM to initialize itself with the information contained in the XML document(s). Once the parsing and initialization of your object model is completed, DOM or SAX isn't used anymore. You can use your own object model to accessed or modify your information without using SAX or DOM anymore. So you manipulate your information using your own objects, and rely on the SAX or DOM APIs to import the information from your ApplicationML file into memory (as a bunch of Java objects). You can think of this object model as an in-memory instance of the information that came was "serialized" in your XML document(s). Changes made to this object model are made persistent automatically, you have to deal with persistence issues (ie, write code to save your object model to a persistence layer as XML).
  3. Create your own Java object model (adapter) that uses DOM to manipulate the information in your document object tree (that is created by the parser). This is slightly different from the 2nd option, because you are still using the DOM API to manipulate the document information as a tree of nodes, but you are just wrapping an application specific API around the DOM objects, so its easier for you to write the code. So your object model is an adapter on top of DOM (ie, it uses the adapter pattern). This application specific API uses DOM and actually accesses or modifies information by going to the tree of nodes. Changes made to the object model still have to be made persistence (if you want to save any changes). You are in essence creating a thin layer on top of the tree of nodes that the parser creates, where the tree of nodes is accessed or modified eventually depending on what methods you invoke on your object model.
medium , which is in turn always wider thanthin.

However, the exact widths are not defined, so one user agent couldset them to be equivalent to 5px ,3px , and 2px , while anothersets them to be 3px , 2px , and1px . Whatever width the user agent uses for eachkeyword, it will be the same throughout the document, regardless ofthe circumstances. If medium is the same ason the available display region and other factors. Under CSS, of course, you can assert more direct control over the way elements are sized and displayed. There are different effects to consider for horizontal and vertical layout, so we'll tackle them separately.

8.2.1. Vertical Formatting

Vertical formatting is much easier to cover, so let's do that first. A good deal of this was