Skip to Content

3 Ways to Center A Div with CSS

In this tutorial, we'll explore three different ways to horizontally and vertically center a div inside its parent element with CSS.

CHILD

Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

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.

.parent {
display: flex;
}

.child {
margin: auto;
}

2. Flexbox

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.

.parent {
display: flex;
justify-content: center;
align-items: center;
}

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.

.parent {
position: relative;
}

.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

Conclusion

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.

Posted by: Josh Rowe
Created: July 08, 2023

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.