In this tutorial, we'll explore three different ways to horizontally and vertically center a div inside its parent element with CSS.
1. Flex Item
This method sets all child element margins to
auto, which evenly distributes space on all sides of the element and centers it horizontally and vertically within its container.
This method utilizes flexbox to center the child element horizontally and vertically within its container. The CSS rules in this example apply to the parent element only. The
justify-content property centers the div horizontally and the
align-items property centers the div vertically.
3. Absolute Positioning & Transform
This method creates an absolute position for the element at 50% from the top and left of its container. The
transform property with the
translate function shift the element back 50% of its width and height, effectively centering itself both horizontally and vertically. Setting the parent container to relative positioning ensures that the child element stays within its boundary.
transform: translate(-50%, -50%);
These are three examples illustrating various ways to center a div element using CSS. Every web application is different, so choose the one that works best for you.