I was working on a CSS challenge, and I encountered an issue. I set display: flex; on the body, and while justify-content is working correctly, align-items is not behaving as expected.
I even changed the background color of the body to see if the problem was with the height, but it wasn’t the problem. The entire page adopted the new color.
Do you have any insights into why I’m experiencing this issue? I saw some posts about the same issue .However no one gave a correct answe or explains why this happens !
I would appreciate your help and advice. Please keep the conversation respectful, as I believe in seeking assistance rather than criticism. Thank you!
Here’s the code :
body{
background-color:rebeccapurple;
display:flex;
align-items:flex-end;
justify-content:center;
}
div {
width: 100px;
height: 100px;
background: #9CCCDB;
}
<div></div>
2
Answers
This is a weird one, so it’s perfectly understandable why it would be confusing. The background color of
<body>
does take up the whole page, but if you examine it with dev tools, you’ll see that it’s only 100px tall (i.e., as tall as that blue block). Why? That question is answered here if you’re curious: Why does styling the background of the body element affect the entire screen?.So the problem actually is the height. To fix it, you could set
<body>
‘s height to the whole viewport height.Do you mean that you’re expecting the smaller box to be at the bottom of the viewport?
It looks like there’s a somewhat unintuitive effect happening as a result of the background color. It is filling the viewport, but if you inspect the DOM and styling with your browser’s debugging tools you see that the
<body>
element only has an inner height of100px
(because of the element it contains).You can define
<body>
to always be the full height of the viewport:As a potential extra enhancement… In my browser the
<body>
has a defaul8px
margin as part of the user agent styling, which you can subtract from the viewport height if you wish:Or you could explicitly control the margins, etc.