In CSS the position property can be used to specify the positioning method we will use for any element.>
The different values for this property are:
- static
- relative
- fixed
- absolute
- sticky
Only when the position property is set once, the elements can be positioned using the top, bottom, left, and right properties.
Let’s now take a look at different position values
static
By default all the HTML elements are positioned static. Elements with such positioning cannot be affected by altering the top, bottom, left, and right properties.
1 2 3 4 | p { position: static; border: 2px solid blue; } |
relative
This positions the element relative to its default/normal position.
We can set the top, bottom, left and right properties to adjust them away from the normal positions.
1 2 3 4 5 6 | p { position: relative; top: 50px; left: 140px; border: 2px solid blue; } |
fixed
This is done to keep the element fixed even when the page is being scrolled.
Once the position is set as fixed, you can position the element using the left, right, top and bottom properties.
1 2 3 4 5 6 7 8 9 10 11 12 13 | p#fixed { position: fixed; top: 50px; left: 60px; padding:5px; background-color: cyan } p#content{ background-color: yellow; width:500px; height: 800px; } |
absolute
This value is used to position the element with respect to its ancestral element.
However, if there’s no ancestral element, the absolute works just like the fixed value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | div#relative { position: relative; width:400px; height: 300px; background-color: cyan; } div#absolute{ position:absolute; background-color: yellow; width:100px; height: 100px; top:50px; left: 50px; } |
sticky
This is, somewhat, a mix of the relative and the fixed values.
The element with sticky positioning moves up and down with the scroller as long as it does not hit the viewport offset.
In simpler words, as you scroll up, the element will move just like any other element until it meets the top edge of the viewport.
After that, it acts like a fixed positioned element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | div#sticky { position: sticky; position: -webkit-sticky;/*to work with safari**/ top: 0; width: 100%; height: 100px; background-color: cyan; } div#content { background-color: yellow; width: 100%; height: 10000px; } |
Overlapping
Positioning can cause the element to overlap in certain situations.
However, we can decide that which element should be on the top of the overlapping stack using the property called, z-index.
Thus if you give a positive value, the element will be at the front (top of the stack) and vice-versa.