5 Ways To Center A DIV in CSS

by|inArticles||2 min read
Center A DIV in CSS
Center A DIV in CSS

To center a div element in CSS can sometimes be a challenge. In this article we explore 5 techniques to center a div.

Using flexbox

Flexbox is one of my favorite options to center a div. In general we use the property display: flex and make use of the flex child orientation by utilizing the CSS properties justify-content or align-items:

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

Even though it looks simple, there are some pitfalls. If we change the direction of our flex parent (flex-row or flex-col) we need to use different CSS properties. (justify-content vs. align-items).

Using grid

Grids are pretty new in web development, but most of the common Web-Browsers support them. Hence, using grids depends highly on which preference you choose in your project. Many developers stick to the following rule: If the constellation of your elements has only one dimension (row, col, etc.), use flexbox. If it gets more complicated, multi-dimensional, use grid. In this case we can center a div by using the CSS property place-content: center

.parent {
    display: grid;
    place-content: center;
}

Using Position

Position is one of the least elegant methods that have been around for a while now. Before flexbox and grid came along, it was one of the common patterns to be used to center a div. In this case we define the parent div as positioned relative, so we can tell the child to place itself absolutely to its parent in the center.

.parent {
     position: relative;   
}

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

Using flex and margin

If you do not want the parent div to decide how it's children should be positioned, you can use flexbox  in combination with the margin property. With this technique you tell the child to calculate the margin to the left and to the right automatically:

.parent {
    display: flex;
}

.child {
    margin: auto;
}

I used this technique also in the article CSS: Pushing a Menu Item to the right

Using grid and margin

Grid works, in terms of margin, very similar as flexbox. Hence, we can use the same pattern to center a div in a grid-like constellation of elements:

.parent {
    display: grid;
}

.child {
    margin: auto;
}

Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

Related Articles

© Copyright 2023 - ersocon.net - All rights reservedVer. 388