Learn CSS position property by examples
Positioning an HTML element is one of the key purposes of CSS.
position property with
right property in CSS is used for that.
position has mainly five different values:
It is going to be an easy and quick one to understand.
static is the default value of the position and keeps the HTML element positioned according to the normal flow of the document.
right doesn't work on the
static positioned element.
Okay I'm going to refer to the offset properties as
tlbrfrom now on
position value to
relative doesn't do anything by itself, the element remains at its normal position in the original document flow but now its position gets affected by the
tlbr properties offset the element relative to its original position.
As we can see from the above example, the relative offset does not affect any other element.
absolute behaves similarly to
relative but the element is also removed from the normal document flow i.e. it is now positioned relative to the closest ancestor block-level element whose position is other than the default
.parent element is having the default position value
static that's why the
.yellow box is positioned relative not to that but to the
Let's see what happens if we change the
.parent position value to
.yellow box is positioned relative to the closest container
But but but...
There is one issue we can see, the yellow box is overlapping the green box, well this is because position value
fixed takes the element out of the document flow and no space is allotted for it.
Q - What if we want to make the green box come above the yellow one?
Ans - We can use the
z-index property for this. Simply put the element with a higher
z-index value comes above the rest.
fixed elements get out of the normal flow of the document, and are positioned relative to the whole HTML itself and it doesn't care if the ancestor like
.parent is positioned
relative or not.
fixed value also makes the element fixed to one place even when we scroll.
Let's increase the
width of the container to see what happens.
sticky value is like a combination of both
By default, it behaves like
relative but when the parent gets scrolled off the screen it behaves like
The red box has
sticky position value with
top: 0 so when its parent box is in the view it acts as a
relative value and remains at its original position in the document flow, but when we scroll the page the parent box scrolls off but the red box sticks to the top of the screen until the whole container is out of the viewport.
So we've learned all the important values of
position property and the examples made it clearer but the best way to learn anything is by doing, don't just sit on the examples I've given in the blog and try to create some examples of your own in Codepen.
👇Please put your codepen links in the comments to showcase your skills and also help other learners.