Understanding relative vs absolute Positioning in Tailwind CSS
Tailwind CSS has two common ways to position elements: relative and absolute. Knowing when to use each one will help you position elements where you want them on the page.
What is relative positioning?
relative positioning means the element stays in its normal spot, but you can move it a little using top, right, bottom, or left. You may want to move it slightly to adjust spacing, alignment, or to create a subtle visual effect. It still takes up space like normal.
This box is relative. It moves slightly with
top-2 and left-2.What is absolute positioning?
absolute positioning means the element is removed from the normal flow of the page. It doesn't take up space like normal. Instead, it is placed exactly where you tell it, inside the nearest relative parent.
This box is relative.
I am absolute inside!
When to Use Them
- Use relative when you need to nudge an element a little without removing it from the flow.
- Use absolute when you need to place an element on top of or inside another element, like adding a label on an image or positioning an icon inside a button.
Key Example Recap
You often use relative on the parent and absolute on the child to position something inside the parent.