create account

Different ways of centering a div with CSS by kushyzee

View this thread on: hive.blogpeakd.comecency.com
· @kushyzee ·
$26.54
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.

![](https://images.ecency.com/DQmVhzNGJ6ebZ1qeKMiKFXtCeTVboXhjWBFeaTrU1in95nU/20221001_214803_0000.jpg)

## 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;
}
```
![](https://images.ecency.com/DQmYeuAsaDrzqX2EEkWLGcoZvBkYLjLvV2bgWmMqwE15Ffv/new1.png)

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.

![](https://images.ecency.com/DQmX39NXHDoLReYVthSw3d2tUKVYeMkPL6Tid7wg8rQt5pY/new2.png)

## 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%;
}
```
![](https://images.ecency.com/DQmX39NXHDoLReYVthSw3d2tUKVYeMkPL6Tid7wg8rQt5pY/new2.png)

## 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
![](https://images.ecency.com/DQmWWFkzk5q56EEgaAUDq9sEvE2sHFfMMKFS5mpzmc9mV6d/new3.png)

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;
}
```
![](https://images.ecency.com/DQmWP5MU2r9uaTiWEzHvbj8hDTjDWK5GUUnT6B1whT9YdaH/new4.png)

## 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

![](https://images.ecency.com/DQmPGSdXxKu2K7pAcCVQEqTVkETtv24yvMfoJ6qh1pmGdDV/new5.png)

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.

![](https://images.ecency.com/DQmXEQiJBLTaAf6sMwK88DC5BxnYpbRk5D5gkNcNDZwF3JC/new6.png)

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:

![](https://images.ecency.com/DQmNxMxcnwZqj7KTVZdqTS2SQPa8G5VHrK94phcSHPcyJmo/new7.png)

## 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: 

![](https://images.ecency.com/DQmNxMxcnwZqj7KTVZdqTS2SQPa8G5VHrK94phcSHPcyJmo/new7.png)

## 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**

![](https://images.ecency.com/DQmbLhPcVduzukxbvrW8pAyEeLpgxqFs1sddNPJCm5xjM4V/img_0.018478079605897074.jpg)

**Connect with me on:**
**Twitter:** **[@kushyzeena](https://twitter.com/kushyzeena)**
**Readcash:** **[@kushyzee](https://read.cash/@Kushyzee)**
<div class = phishy> 
<strong>Lead image: created with Canva</strong>
</div
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 95 others
👎  
properties (23)
authorkushyzee
permlinkdifferent-ways-of-centering-a
categoryhive-169321
json_metadata{"links":["https://twitter.com/kushyzeena","https://read.cash/@Kushyzee"],"image":["https://images.ecency.com/DQmVhzNGJ6ebZ1qeKMiKFXtCeTVboXhjWBFeaTrU1in95nU/20221001_214803_0000.jpg","https://images.ecency.com/DQmYeuAsaDrzqX2EEkWLGcoZvBkYLjLvV2bgWmMqwE15Ffv/new1.png","https://images.ecency.com/DQmX39NXHDoLReYVthSw3d2tUKVYeMkPL6Tid7wg8rQt5pY/new2.png","https://images.ecency.com/DQmX39NXHDoLReYVthSw3d2tUKVYeMkPL6Tid7wg8rQt5pY/new2.png","https://images.ecency.com/DQmWWFkzk5q56EEgaAUDq9sEvE2sHFfMMKFS5mpzmc9mV6d/new3.png","https://images.ecency.com/DQmWP5MU2r9uaTiWEzHvbj8hDTjDWK5GUUnT6B1whT9YdaH/new4.png","https://images.ecency.com/DQmPGSdXxKu2K7pAcCVQEqTVkETtv24yvMfoJ6qh1pmGdDV/new5.png","https://images.ecency.com/DQmXEQiJBLTaAf6sMwK88DC5BxnYpbRk5D5gkNcNDZwF3JC/new6.png","https://images.ecency.com/DQmNxMxcnwZqj7KTVZdqTS2SQPa8G5VHrK94phcSHPcyJmo/new7.png","https://images.ecency.com/DQmNxMxcnwZqj7KTVZdqTS2SQPa8G5VHrK94phcSHPcyJmo/new7.png","https://images.ecency.com/DQmbLhPcVduzukxbvrW8pAyEeLpgxqFs1sddNPJCm5xjM4V/img_0.018478079605897074.jpg"],"tags":["hive-169321","stem","neoxian","pob","hive","vyb","oneup","palnet","coding"],"app":"ecency/3.0.34-mobile","format":"markdown+html"}
created2022-10-01 21:53:36
last_update2022-10-01 21:53:36
depth0
children8
last_payout2022-10-08 21:53:36
cashout_time1969-12-31 23:59:59
total_payout_value13.288 HBD
curator_payout_value13.251 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,148
author_reputation75,924,249,520,559
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,102,216
net_rshares40,823,618,352,975
author_curate_reward""
vote details (160)
@charlrific ·
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!
properties (22)
authorcharlrific
permlinkre-kushyzee-2022102t122224674z
categoryhive-169321
json_metadata{"tags":["hive-169321","stem","neoxian","pob","hive","vyb","oneup","palnet","coding"],"app":"ecency/3.0.28-vision","format":"markdown+html"}
created2022-10-02 11:22:30
last_update2022-10-02 11:22:30
depth1
children1
last_payout2022-10-09 11:22:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length203
author_reputation12,515,265,882,572
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,115,758
net_rshares0
@kushyzee ·
Centering divs is something we all found difficult as a newbie, but we get better at it with experience. Thanks for reading 
properties (22)
authorkushyzee
permlinkre-charlrific-2022102t145341809z
categoryhive-169321
json_metadata{"tags":["hive-169321","stem","neoxian","pob","hive","vyb","oneup","palnet","coding"],"app":"ecency/3.0.34-mobile","format":"markdown+html"}
created2022-10-02 13:53:42
last_update2022-10-02 13:53:42
depth2
children0
last_payout2022-10-09 13:53:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length124
author_reputation75,924,249,520,559
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,118,712
net_rshares0
@curation-cartel ·
![1UP-PIZZA.png](https://files.peakd.com/file/peakd-hive/curation-cartel/23xediR4hotaNsS5pUJrmYVg3YGeTLpui41uCij2jhUDZ4uFT84zoGJf8a8VnfELXLJgt.png) |  <div class="phishy"><u><h4>You have received a __1UP__ from @gwajnberg!</h4></u></div> The @oneup-cartel will soon upvote you with:<hr> __@oneup-curator, @stem-curator, @vyb-curator, @pob-curator, @neoxag-curator, @pal-curator__ <hr>_And they will bring !PIZZA 🍕._
-|-

<sup>[Learn more](https://peakd.com/hive-102223/@flauwy/the-curation-cartel-1up-trigger-smart-voting-mana-and-high-delegation-returns-for-14-different-tribes) about our delegation service to earn daily rewards. Join the Cartel on [Discord](https://discord.gg/mvtAneE3Ca).</sup>
properties (22)
authorcuration-cartel
permlinkre-different-ways-of-centering-a-20221002t162135z
categoryhive-169321
json_metadata"{"app": "beem/0.24.26"}"
created2022-10-02 16:21:36
last_update2022-10-02 16:21:36
depth1
children0
last_payout2022-10-09 16:21:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length698
author_reputation1,123,173,135,173
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,121,863
net_rshares0
@diyhub ·
<div class="pull-right"><a href="https://peakd.com/trending/hive-189641"><img src="https://cdn.steemitimages.com/DQmV9e1dikviiK47vokoSCH3WjuGWrd6PScpsgEL8JBEZp5/icon_comments.png"></a></div>

#### 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](https://peakd.com/trending/hive-189641) so we never miss your content. We also have a [discord server](https://discord.gg/mY5uCfQ) 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!
properties (22)
authordiyhub
permlinkre-different-ways-of-centering-a-20221002t174212z
categoryhive-169321
json_metadata"{"app": "beem/0.24.26"}"
created2022-10-02 17:42:12
last_update2022-10-02 17:42:12
depth1
children0
last_payout2022-10-09 17:42:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,017
author_reputation360,077,782,901,426
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,123,825
net_rshares0
@gwajnberg ·
I didnt know about all these options
!1UP

<a href="https://discord.gg/zQrvxAu7mu">
<img src="https://files.peakd.com/file/peakd-hive/thecuriousfool/23wCNFDyCLJu1v77TTg2MYKkd7XWkgF9fhiLujTDAaLaUz7H4AaQkDentB5UMVS8FcrVs.png"></a>
properties (22)
authorgwajnberg
permlinkre-kushyzee-2022102t101941148z
categoryhive-169321
json_metadata{"tags":["hive-169321","stem","neoxian","pob","hive","vyb","oneup","palnet","coding"],"app":"ecency/3.0.34-mobile","format":"markdown+html"}
created2022-10-02 16:19:42
last_update2022-10-02 16:19:42
depth1
children1
last_payout2022-10-09 16:19:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length228
author_reputation148,893,337,789,229
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,121,828
net_rshares0
@kushyzee ·
Now you know them 😊 thanks for the token 
properties (22)
authorkushyzee
permlinkre-gwajnberg-2022102t192228904z
categoryhive-169321
json_metadata{"tags":["hive-169321","stem","neoxian","pob","hive","vyb","oneup","palnet","coding"],"app":"ecency/3.0.34-mobile","format":"markdown+html"}
created2022-10-02 18:22:30
last_update2022-10-02 18:22:30
depth2
children0
last_payout2022-10-09 18:22:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length41
author_reputation75,924,249,520,559
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,124,785
net_rshares0
@monioluwa ·
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. 
properties (22)
authormonioluwa
permlinkre-kushyzee-rj6qak
categoryhive-169321
json_metadata{"tags":["hive-169321"],"app":"peakd/2022.07.1"}
created2022-10-03 16:11:09
last_update2022-10-03 16:11:09
depth1
children1
last_payout2022-10-10 16:11:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length371
author_reputation14,336,654,616,518
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,156,243
net_rshares0
@kushyzee ·
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 
properties (22)
authorkushyzee
permlinkre-monioluwa-2022104t20523077z
categoryhive-169321
json_metadata{"tags":["hive-169321"],"app":"ecency/3.0.34-mobile","format":"markdown+html"}
created2022-10-04 19:52:33
last_update2022-10-04 19:52:33
depth2
children0
last_payout2022-10-11 19:52:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length188
author_reputation75,924,249,520,559
root_title"Different ways of centering a div with CSS"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id117,187,737
net_rshares0