CSS positioning properties
With CSS positioning properties, you can specify where and how elements should be positioned.
This lesson focuses on:
- Positioning elements
- Stacking elements
Positioning elements
The position of an element is set with the position property.
Possible values for the position property:
-
static
The element will have its default position given to it by the normal flow of a webpage.
-
relative
The element will be moved from its default position based on specification and will be displayed as such.
-
absolute
The element will be displayed at a set of specified coordinates relative to the block in which it is contained.
-
fixed
The element will be displayed at a set of specified coordinates relative to the browser window.
NOTE: The position property is often used together with some other properties!
Properties used together with the position property:
-
left
Sets the left coordinate of an element
-
right
Sets the right coordinate of an element
-
top
Sets the top coordinate of an element
-
bottom
Sets the bottom coordinate of an element
Example:
<html>
<head>
<style type="text/css">
<!--
p.two{
position: absolute;
left: 20;
top: 40;
}
h2{
position: relative;
right: 40;
bottom: 60;
}
-->
</style>
<title>Positioning elements</title>
</head>
<body>
<p>
This paragraph has a default position.
</p>
<p class="two">
This paragraph has an absolute position.
</p>
<h4>This heading has a relative position.</h4>
</body>
</html>
Output:
This paragraph has a default position.
This paragraph has an absolute position.
This heading has a relative position.
In the above example, there are two paragraphs and one heading. The first paragraph has its default position. The second paragraph has an absolute position that is 20 pixels from the left and 40 pixels from the top relative to the block in which it is contained. The heading has a relative position that is 40 pixels from the right and 60 pixels from the bottom relative to its default position.
Stacking elements
Elements are stacked using the z-index property. By stacking elements, you can specify which elements will appear in front of other elements. By default, elements have a z-index of 0.
Example:
<html>
<head>
<style type="text/css">
<!--
img
{
position:absolute;
left:0px;
top:0px;
z-index:-1
}
-->
</style>
</head>
<body>
<img src="apple.jpg" width="100" height="180">
<p>
This paragraph will appear stacked on top of the image
because it has a higher <b>z-index</b>.
The <b>z-index</b> of this paragraph is 0,
while the <b>z-index</b> of the image is -1.
</p>
</body>
</html>
Output:
In the above example, there is a paragraph and an image. The z-index of the paragraph is 0 (by default). The z-index of the image is -1. The paragraph will appear stacked on top of the image because it has a higher z-index.




