Position HTML elements

You can use PHP to position HTML elements. Here's how.

By Matt Rotter, Charity Kahn, and Paul Anderson

To use positioning on an element, you must first declare its position property to be absolute or relative:

H1 { position: absolute }

Then you can add whatever positioning properties you like. For instance, the following code places <H1> text inside a box that's 150 pixels from the top of the page and is 200 pixels wide by 200 pixels high:

H1 { position: absolute; top: 150px; width: 200px; height: 200px }

Of course, you probably don't want all your <H1> elements to appear in the same spot. This is where in-line styles, ID selectors, and the <DIV> and <SPAN> elements come in handy. For example, this code positions only the contents of this particular <DIV> element:

<DIV style="position: absolute; top: 200px; left: 200px; width: 200px; height: 200px; background-color: red">This is text in a red 200-by-200-pixel box that is 200 pixels from the top and left edges of the window.</DIV>

Absolute positioning offsets elements from the edges of the browser window, while relative positioning places elements into the flow of the document—that is, offsetting them from the previous element in the HTML code. This lets you place objects in relation to each other without having to specify exactly where on the page to draw each object.

In the following example, the first line of text flows normally across the page. The second line, within a <SPAN> that uses the positioning styles outlined in the offset ID, is 50 pixels below and 25 pixels to the right of the element above it. (The top and left properties leave space above and to the left of the element to which their style is applied.)

<STYLE type="text/css">
#offset { position: relative;
     top: 50px;
     left: 25px

This text will flow normally across the page, while the next line of text will be offset from the end of this line.

<SPAN id="offset">This text is offset from the above line—50 pixels on top and 25 pixels on the left.</SPAN>

Note: The examples on this page work only with browsers of version 4.0 and later.

Matt Rotter and Charity Kahn are software engineers for

Paul Anderson is an associate technical editor for CNET

Editor's Picks