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?
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.
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
.