Search code examples
htmlcssflexboxcenteringabsolute

Difference between centering a div using flexbox and absolute position


If I have a flexbox, I can center a div horizontally and vertically, using

justify-content: center;
align-items: center;

and I can use the following code in the case of position: absolute

top: 50%;
left: 50%;
transform: translate(-50%, -50%);

What is the difference between the both and which is the more preferred way?


Solution

  • The CSS position documentation describe absolute position as:

    The element is removed from the normal document flow, and no space is created for the element in the page layout.

    So essentially, while an absolute element looks like it is centered around its container, think of it more like "hovering" above the container and all the container's child elements (Try the interactive example in the link). This is different from flexbox, when your element is normally centered in the container while still taking space inside it.

    Absolute positioned element is broken from document flow

    Because the flexbox way is usually what you want, I would say it is the preferred way. However, sometimes you want the behavior of absolute positioning, in which cases it is absolutely (heh) okay to use position: absolute.