Positioning elements in CSS

Using style sheets along with the <SPAN> and <DIV> tags, you can specify the location of text or images down to the pixel.
This is possible with versions 4 and higher of Netscape and Internet Explorer; however, the technique is still problematic and may cause some compatibility issues.

Relative and absolute positioning

Absolute positioning {position: absolute} is determined relative to the upper-left corner of the browser window. The coordinates of a point are given from top to bottom (top) and from left to right (left).

Relative position is defined in relation to other page elements, meaning that the elements contained in the DIV or SPAN tags will be positioned based on the HTML elements preceding them.

Positioning text

Let's place the text "How does it work?" 80 pixels from the top of the window and 100 pixels from the left:

<HTML>
<BODY>
<SPAN style="position: absolute; top: 80 px; left: 100 px;">

How does it work?
</SPAN>
</BODY>
</HTML>

There are other ways to do this, such as:

<HTML>
<HEAD>
<STYLE>
<!--
.test{position: absolute; top: 80px; left: 100px; color: black; font-size: x-large}
-->
</STYLE>
</HEAD>
<BODY>
<DIV class=test>
How does it work?
</DIV>
</BODY>
</HTML>

Positioning an image

Let's place the image "test.jpg" 80 pixels from the top of the window and 100 pixels from the left (the image is 103x61):

<HTML>
<BODY>
<SPAN style="position: absolute; top: 80 px; left: 100 px;width: 103px; height: 61px">
<IMG SRC="test.jpg" >
</SPAN>
</BODY>
</HTML>

It is important to specify the size of the image in style sheets, to reduce the risks of browser incompatibility.

Superimposing elements

Let's superimpose the text "How does it work?" on top of the image "test.jpg":

<HTML>
<BODY>
<SPAN style="position: absolute; top: 30 px; left: 100px;width: 103px; height: 61px">
<IMG SRC="test.jpg" >
</SPAN>
<SPAN style="position: absolute; top: 50 px; left: 100 px;">
How does it work?
</SPAN>
</BODY>
</HTML>

Using this syntax, you can superimpose both text elements and images.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jean-François Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.
Related
This document, titled « Positioning elements in CSS », is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).

Subscribe To Our Newsletter!

The Best of CCM in Your Inbox

Subscribe To Our Newsletter!