Centering Divs

Centering a div can sometimes be confusing here are some ways to center divs via CSS

Margin Auto

<div>
    < div class=“margin-c”>center me</div>
</div>
.margin-c {
    margin: 0 auto;
    max-width: 150px;
}

This will take the size of “.margin-c” and automatically place margin to the left and right of the the div.

Flex Box Centering

Flex is the new age way of aligning children in the div. The nice thing about using flex is that it can be used in a responsive manner. Meaning less worrying about having responsive containers!

*by default using flex makes the direction in a row.

Flex-Box Vertical Alignment

<div class=“flex-container”>
    <div class=“child”></div>
</div>
.flex-container {
    display: flex;
    justify-content: center;
}
.child {
    width: 50px;
    height: 50px;
}

Flex-Box Vertical Alignment

If you want to vertically center the child you can add ”align-content: center”

.flex-container {
    display: flex;
    justify-content: center;
    align-content: center;
}
.child {
    width: 50px;
    height: 50px;
}

Flex-Box Responsive

Lets say you want to make the child responsive add ”flex-wrap: wrap;”

.flex-container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
}
.child {
    width: 50px;
    height: 50px;
}

Position Absolute / Relative

If you want to position an element and make sure it stays in place, like background objects, icons, div, or any thing you want!

Setting the top and left will only bring the top of the element to the center, you can use negative margins to position it to the center. However, to get true center use “transform: translate ()”,

<div class=“container”>
    <div class=“child”></div>
</div>
.container {
    position: relative;
}
.child {
   position: absolute;
   width: 50px;
   height: 50px;
   top: 50%;
   left: 50%;
   transform: translate( -50px, -50px ); // center vertical and horizontal
}

Centering Divs

Copy to clipboard
View CSS
View HTML