0

I want to make all my content/elements in tag to be centered of the browser or viewport.

I did this initially:

body {
    background-color: hsl(212, 45%, 89%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

But my is not at the center vertically. You can refer here for the image.

However, after I added height: calc(100vh - 1px); to my code, then only it will be at the center of the browser/viewport perfectly. Full code:

body {
    background-color: hsl(212, 45%, 89%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 1px);
}

You can referhere for the image and can see the content is in the center now.

My understanding is, with display:flex, justify-content: center, align-items: center, I would be able to make all the child elements to be centered. Obviously, my understanding is wrong.

Can anyone explain this?

Thank you in advance!

Adora
  • 11
  • 2
  • Hello, give a border to body, then test with and without height. It will explain itself :) – G-Cyrillus Feb 12 '23 at 08:07
  • 1
    The elements are probably in the center of the flex box, but the flex box's height is not at all determined in your initial attempt, so it will not take up the full height of the screen. Just out of curiosity, what will happen if you set the height to 100vh, without the calc? – Leonardum Feb 12 '23 at 08:17

1 Answers1

1

Height of <body> depends on its content, that's why your trick won't work until you make it the same height as the viewport (-1px to avoid scrollbar I guess). Give a background colour to <body> and you will see.

  • yup, you need to define body height with flex since the default behavior with flex is for the outer divs to conform to the inner elements and content. Hence why it behaves like it's reacting to its content and viewport. – Michael Martell Feb 12 '23 at 10:23
  • Thank you folks. You all explained it all I really appreciated that! Even with a height: 100vh, it will fit in the center perfectly too! – Adora Feb 12 '23 at 13:32