Different ways of centering a div with CSS

Centering a div is one of the worst nightmares of most programmers and that's because some of the methods only work in specific conditions. You might be able to center a div appropriately in one project but you won't be able to use the same method in another project. There are a lot of ways to center a div vertically, horizontally, and both but I will only talk about the most common methods.

Centering a div horizontally with margins

Let’s assume a very simple webpage with a body, a div with 60% width, and some texts inside the div

<body>
    <div>
        <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Est harum repellat, quidem placeat, tenetur error nam quaerat consequuntur corrupti, quibusdam qui illo odit obcaecati. Vel, incidunt. Ipsa neque doloribus perferendis.</p>
    </div>
</body>
body {
    font-size: 1.8rem;
    background-color: darkgray;
}

div {
    width: 60%;
    padding: 1em;
    background-color: red;
    color: white;
}

In order to center that div in the middle of the page horizontally, we just have to apply margin-inline: auto; You can also do margin: 0 auto; where the 0 represents the top and bottom margin while the auto represents the left and right margins which are also called margin-inline.

Centering a div horizontally with CSS position and translate

Using the same code as before, we can also center the grey box containing texts using CSS position and translate properties. The first thing you will have to do is to apply position: relative on the direct parents of the div and in this case it’s the body tag. If you don’t specify a relative position, the div will be positioned relative to the root element, which means the html tag and in this case, it doesn’t really matter because the body and html tags are basically in the same position.

body {
    position: relative;
}

The next thing is to give a position: absolute to the div element, then set left to 50%, this will push the div to the right, and now we can use the translate property to shift it into position. The code will now look like this:

div {
    position: absolute;
    left: 50%;
    translate: -50%;
}

Centering a div horizontally with flexbox

Flexbox is the easiest way to center anything, both horizontally and vertically (we will get to that later). We just have to apply display: flex on the parent (the body) and set justify-content to center.

body {
    display: flex;
    justify-content: center;
}

And that’s it; you don’t need to do any extra thing. Applying a flex on the container can change the layout of your design if there are other items there. Let's assume we have another div in the body element, once we apply a display: flex the two divs will be positioned side by side, but I want them to be arranged vertically. So I can just use flex-direction: column but that will bring another problem: both divs won’t be centered anymore

We can easily fix that with the align-items property, instead of justify-content. You just have to adapt the code to suit the layout of your design and it will work as before. The new code will now be:

body {
    display: flex;
    align-items: center;
    flex-direction: column;
}

Centering a div vertically with CSS position and translate

Centering a div vertically can really be a nightmare because most people forget that they will need to set a height on the parent element. For example; we are going to use the same code as before but this time we will be centering it vertically, it’s the opposite of what we did with the horizontal centering.

body {
    position: relative;
}

div {
    position: absolute;
    top: 50%;
    translate: 0 -50%;
}

The translate property is now 0 -50% and that’s because 0 represents the x-axis, while -50% represents the y-axis. If you specify only one value, it’s going to be taken as the x-axis. Doing the above code won’t work as expected, we are going to have a very weird result

The div has been pushed out of the page and that’s because we didn’t specify a height on the parent (the body). We can easily fix that with min-height: 100vh. It’s usually better to use min-height, instead of just using height, it’s more responsive. You can use any height value and it totally depends on what you’re working on. I used 100vh because most landing page designs usually take up the entire viewport, especially if it’s the hero section. After giving the body a min-height, the div will be centered as expected.

We can combine both methods of centering horizontally and vertically and place the div in the center of the page. This is what the code looks like:

div {
    position: absolute;
    top: 50%;
    left: 50%;
    translate: -50% -50%;
}

And this will be the outcome:

Centering a div vertically with CSS flexbox

Again, this is also the easiest way to center a div vertically, and just like in the previous method, we also need to set a min-height before it can work appropriately.

body {
    display: flex;
    align-items: center;
    min-height: 100vh;
}

And just like that, we have the div vertically centered. From here we can also apply the horizontal centering and have the box directly in the middle. The code for that is:

body {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
}

And the below result will be produced:

Conclusion

Centering a div or any other item on a webpage can be difficult at first but knowing the right method to use in different situations can make it very easy and you will get better at it with experience. All the methods I mentioned in this article will work in all situations, but in some cases, you will have to tweak things a bit to fit the particular project you are working on, just in case the usual method doesn’t work.

Thanks for reading

Connect with me on:
Twitter: @kushyzeena
Readcash: @kushyzee

Lead image: created with Canva


0
0
0.000
8 comments
avatar

This will be really helpful, especially for newbies.
I had really hard times centering divs when I started learning. There are even some things I've discovered from his article.
Thanks for sharing this!

0
0
0.000
avatar

Centering divs is something we all found difficult as a newbie, but we get better at it with experience. Thanks for reading

0
0
0.000
avatar

I didnt know about all these options
!1UP


0
0
0.000
avatar

Now you know them 😊 thanks for the token

0
0
0.000
avatar

Thank you for sharing this amazing post on HIVE!

Your content got selected by our fellow curator tibfox & you just received a little thank you upvote from our non-profit curation initiative!

You will be featured in one of our recurring curation compilations which is aiming to offer you a stage to widen your audience within the DIY scene of Hive.

Make sure to always post / cross-post your creations within the DIYHub community on HIVE so we never miss your content. We also have a discord server where you can connect with us and other DIYers. If you want to support our goal to motivate other DIY/art/music/gardening/... creators just delegate to us and earn 100% of your curation rewards!

Stay creative & hive on!

0
0
0.000
avatar

I really do not understand how you guys find a way to wrap your head around CSS stylings.😅 I've tried to learn it multiple times without any luck and that's one of the reasons why I don't really like the Frontend part of the web.

And you're right, Flex does make everything a bit easy, and using Sass helped me cope with the whole thing for a while.

Nice work chief.

0
0
0.000
avatar

I studied CSS for a very long time until I became very comfortable with it, I know how hard it can be and some people usually run away from frontend because of it 😆

Thank you for reading

0
0
0.000