CSS - Ways to Center Your Divs

Background

Centering your div blocks both horizontally and vertically is a tricky tasky. Today I’m going to show you four ways to do it. So let’s do eeetttt!

1. Transform Technique

Make the parent div position relative so the child position will based on parent’s position. Next to move it top and left 50% and transform back 50% in both x & y-axis.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Transform
.hero-image1 {
background: #3498db;
height: 100vh;
position: relative;
}

.hero-text1 {
text-align: center;
position: absolute;
top: 50%;
left: 50%;
color: white;
transform: translate(-50%, -50%);
}

2. FlexBox

Flexbox is the easiest way to center a div. It’s a newer feature in css, the unforunately thing is some old browsers don’t support it. (sign…) Basically you set display to flex and both align-items and justify-content to center.

1
2
3
4
5
6
7
8
9
10
11
12
13

.hero-image2 {
background: #34495e;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}

.hero-text2 {
text-align: center;
color: white;
}

3. Table Cell

Table cell method is an old school way of doing this. This method was popular when web layout is organized by table, which is still popular with email templates.

Basically you set parent div with display table and set child display to table-cell. Also set the child with text-align center and vertical align middle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Table Cell
.hero-image3 {
background: #e74c3c;
height: 100vh;
width: 100%;
display: table;
}

.hero-text3 {
text-align: center;
display: table-cell;
vertical-align: middle;
color: white;
}

4. Fixed width element

This technique will only work with fixed width element. This will also work with older browsers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.parent {
position: relative;
}

.child {
width: 300px;
height: 100px;
padding: 20px;

position: absolute;
top: 50%;
left: 50%;

margin: -70px 0 0 -170px;
}