A Beginners Guide to Centering in CSS

Introduction

If you’re new to HTML & CSS or just starting to learn how to style your websites/applications, It can be quite frustrating. Every front-end developer will have to come across centering an element in their career eventually. This article will show you 5 different ways of centering a Div using basic HTML & CSS.

Photo by Ales Nesetril on Unsplash

Using CSS Positioning:

We start by setting the parent element’s position to relative.

.parent { 
position: relative;
}

Then setting the child element position to absolute. And our top, left, right, bottom properties to 0 along with defining margin to auto.

.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}

Using Positioning + Transform:

For this one, we set our parent element’s position to relative.

.parent { 
position: relative;
}

Then move our child element to 50% from the top and left of the parent element.

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

Using Absolute + Negative Margin:

Once again, we start by setting our parent element’s position to relative.

.parent { 
position: relative;
}

And now set our child element’s position to absolute. Set the top and left to 50%. And set the margin-left & margin-top to -50px

.parent { 
position: absolute;
top: 50%;
left: 50%;
tranform: translate(-50%, -50%);
margin-left: -50px;
margin-top: -50px;
}

Notice how margin-left and top are -50px. It’s important to know that it’s -50px because half of the child element’s given the size of 100px. Whatever size you give your child element, the margin-left and margin-top should be half of that.

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

Using CSS Grid:

With CSS Grid, we don’t have to set our position to anything. We just set our parent element’s display to grid.

.parent { 
display: grid;
}

CSS grid automatically centers everything for us by just giving the align-self and justify-self properties a value of center.

.child {
align-self: center;
justify-self: center;
}

Another way easier way of centering with CSS Grid is. Giving your parent element a display of grid and using the place-items tag and giving a value of center.

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

Using Flex:

Now with flex, all we have to do is have our parent element display flex and set justify-content and align-items center, and it will automatically center it for you.

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

Resources:

Below are some more learning resources on CSS

Software Engineering Student at Flatiron School New York City