How do I use css position properties?
-
This article looks at the following position CSS properties relative, absolute, fixed and sticky.
To demonstrate CSS position properties we will create a box layout using the following HTML and CSS.
HTML.
... <div class="container"> <div class="box box-1">Box 1</div> <div class="box box-2">Box 2</div> <div class="box box-3">Box 3</div> </div> ...
CSS.
... .container { background-color: cadetblue; width: 700px; height: 600px; } .box { width: 350px; height: 100px; font-size: 25px; color: #fff } .box-1 { background-color: chocolate; } .box-2 { background-color: green; } .box-3 { background-color: pink; } ...
The result is:
The default position is static
The relative position is positioned relative to its normal position.
From the CSS above if we change .box-2 to a relative position. Then we can change the position using top, left, right, and bottom
... .box-2 { background-color: green; position: relative; right: 50px; } ...
The result is as seen below. Negative values can also be used.
Changing the width and height of Box2 will keep the other boxes in their static position and will only change the size of Box2.
The absolute position is positioned relative to its nearest parent element. It is used to position elements independent of other elements.
Changing the original CSS for .box-1 to use absolute position.
... .box-1 { background-color: chocolate; position: absolute; } ...
As seen the element Box 2 appears to have gone however, it is behind Box 1, this is because the absolute position took the Box 1 out of the normal flow.
The parent element of box-1 is the div element with class of container.
If we make the position of box-1
bottom: 0
... .box-1 { background-color: chocolate; position: absolute; bottom: 0 } ...
The result is seen below: Box-1 gets places out side of its parent element because by default the container element has position of static and move according to the body element.
If we change box-1 parent element to be anything other than static, then box-1 moves according to its parent element.
... .container { background-color: cadetblue; width: 500px; height: 400px; position: relative; } ...
The result is:
Box 1 can be moved around relative to its parent element, using left, right, top and bottom properties.
Box 1, Box 2, and Box 3 can be layered using z-index CSS property with the higher numbers taking priority.
The position fixed is positioned relative to the viewport. It can be positioned using left, right, top and bottom properties. Using the fixed position the element stays in the same place even when scrolling.
In the image below using the fixed position, as you scroll the container remains fixed to one position.
Sticky position
The sticky position makes an element remains visible as you scroll down, until you have scrolled passed its parent element. Occasionally used in navigation and single page websites.
© Lightnetics 2024