At times, when you want to decide on the CSS position property to use, you will find yourself debating on CSS absolute vs CSS fixed argument. Well, both of these have their benefits and use cases.
So, before we finally get to answer the question on CSS absolute vs CSS fixed dilemma, it is best to understand what both these CSS position properties really mean.
Well, as the name suggests, it is freely positioned with respect to the other elements in their parent element, so long as their parent element does not impose this restriction.
Absolute positioning will make it possible for the element to defy the default CSS position – block, and give it the ability to be placed freely on the parent element.
However, the catch is that it is can be limited by it’s parent’s boundaries! What do I mean by this. Suppose we have this HTML code:
<div class="parent">
Parent A
<div class="child">
A child of Parent A
</div>
</div>
Then we have this CSS position definition:
.parent {
.child {
position: absolute;
}
}
The child element will be free to position itself anywhere on the document. It will be unbound as long as the parent does not restrict it.
So, what if we want the child element to only have CSS absolute position, and be contained within the parent element? Well all we need to do is to set the parent element to have a relative position like so:
.parent {
position: relative;
.child {
position: absolute;
}
}
This should now ensure that the child element will always have CSS absolute position, BUT always appear in the parent element.
So, what if we want the child element to appear anywhere on the document, unbound by the parent element? This introduces CSS fixed position, which will now make it possible to help you settle your CSS absolute vs CSS fixed debate.
Using the above example of parent and child, when the child is specified as having a fixed position, then it’s positioning will be with respect to the DOM.
It will never be bound by the parent’s position property. So, what this means is that even if we have this:
<div class="parent">
Parent A
<div class="child">
A child of Parent A
</div>
</div>
Then we have this in our CSS:
.parent {
position: relative;
.child {
position: fixed;
}
}
This is the same as not even specifying CSS position on the parent, because the child will not adhere to it.
At this point, it is now clear on which option to go with whenever you find yourself on the CSS absolute vs CSS fixed uncertainty.
In such few words, you now have an understanding of CSS fixed and CSS absolute position. Hopefully, your CSS absolute vs CSS fixed conundrum has been demystified.
Well, that’s if for today!