1. Technology

CSS Positioning Examples

Sample Code for Positioning with CSS

By

Relative Positioning

Example 1 shows how text and images flow in HTML and then have the position set by a style.

First you place the image or element that you'd like positioned relatively into the flow of the page. It's a good idea to look at where the element will display in the flow without any positioning, so that you know how you'll need to position it.

This is the text that you would like the image to follow. Then you place the image...
 <img src="cecb2.gif" width=32 height=32 alt="CECB">

See the image in the flow (no positioning).

Then add your position styles into the document to change the location of the element. Remember that relative positioning places the positioned element relative to it's normal location in the flow.

<p> This is the text that you would like the image after. Then you place the image and position it underneath the text...
<img src="cecb2.gif" width="32" height="32" alt="CECB" style="position:relative; left:15px; top:-15px;" /></p>

See the image with positioning.

Absolute Positioning

Example 2 shows how absolute positioning places objects in relation to the upper left corner of the page.

As with the relative positions example, you should always place your elements in the flow to see where they land in the normal flow of the page.

<p>If you put an image between text blocks on a page
 <img src="/library/graphics/cecb2.gif" width=32 height=32 alt="CECB">
 It will affect the position of any text or other elements after it.</p>

See the image in the flow (no positioning).

Unlike with relative positioning, when you position an element absolutely, it is positioned completely outside the flow of the document. The browser positions the element relative to the 0,0 x,y position in the upper left corner of the browser window.

<p>If you put an absolutely positioned image on a page
<img src="cecb2.gif" width="32" height="32" alt="CECB" style="position:absolute; left:200px; top:500px;" />
It will not affect the position of any text or other elements after it.</p>

See the image with positioning.

You can also position your elements with percentages. 100% left would be on the right-most margin of the screen, no matter how wide the screen was. And 100% from the top would be at the very bottom of the screen.

This image would be placed at the bottom of the first screen-full in the browser and half-way across the middle of the document.

<img src="cecb2.gif" width="32" height="32" alt="CECB" style="position:absolute;left:50%; top:100%;" />

See the image with percentage positioning.

©2014 About.com. All rights reserved.