Centering Complete body element

I was wondering what approach should one take to center the body element both vertically and horizontally. Flexbox can only be used to center element under parent container how can one center body element. I am using margin: (random) auto; to center the body element

1 Like

Hi @akshay1!

margin: 0 auto is a tried and tested old-school technique for horizontally centering content, but it is no use for vertical centering.

For horizontal and vertical centering, Flexbox is fine. Remember that you’ve got the <html> element wrapping the <body> element. This still counts as part of the content and can be used to hang the flexbox declarations off.

Try playing with this:

body {
  width: 50%; /* make the body only span 50% of the html width */
  border: 1px solid black /* give it a border so you can easily see what space it takes up  */
}

html {
  width: 100%; /* make sure the HTML element spans the entire width and height of the viewport */
  height: 100%;
  display: flex; /* make it a flex container */
  justify-content: center; /* center the content along the main axis (horizontally by default if your browser is set to use a left-to-right or right-to-left language) */
  align-items: center /* center the content along the cross axis (vertically by default...) */
}
2 Likes

never thought I could assign flex to the parent html container. Thankyou so much for clearing this out.

1 Like

Hello, akshay1 and chrisdavidmills!

As chrisdavidmills explained, for your purpose akshay1, Flexbox is fine and is a more modern technique than margin: auto. But actually, I always use it like:

<style>
  .centrediv {
     position: absolute;
     top: 0;
     bottom: 0;
     left: 0;
     right: 0;
     margin: auto;
     width:  50%;
     height: 50%;
  }
</style>

<div class="centrediv"></div>

The above example gives you a horizontally and vertically centred div element. Note that it requires the size of the div element, i.e. the specific width and height.

Have a nice centring!

@safejourney that is also a nice technique, thanks for sharing! Note that this can be used on the <body>, if you don’t want to use an additional container <div>.

Oops! It’s my mistake!
My explanation is not for the body element.

So, yes, just for sharing!
Have a nice day!