Reputation: 6613
HTML Code:
<!DOCTYPE html>
<html>
<head></head>
<body>
<link rel="stylesheet" type="text/css" href="style.css">
<div class="sheet" style="width:80%;max-width:1024px;height:400px;"></div>
</body>
</html>
CSS Code:
html,
body {
min-height: 100%;
margin: 0;
padding: 0
}
body {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.sheet {
background-color: red
}
What I expected to see was a red rectangle floating in the middle of the screen but what I get is the rectangle being at the top-middle.
It never worked in FF, it worked in chrome before adding the DOCTYPE tag but after that it no longer works in chrome either.
What does work is when I use height
instead of min-height
but I don't want to pin down the height value to the size of the screen since I may need it when containers long enough to scroll come into play.
Upvotes: 3
Views: 6680
Reputation: 149
Set the min-height property to 100vh
(viewport height). Your body's minimal height will then be 100% of the viewport.
Upvotes: 7
Reputation: 288670
Because it's a circular reference.
You can set min-height: 100%
to html
. That means it will be at least as tall as the viewport, but can grow taller if the contents (i.e. body
) are taller.
Since the height of html
depends on the height of body
, the height of body
can't depend on the height of html
. So if you set min-height: 100%
to the body
, it won't work.
However, you can use explicit height:
height: 100%
to html
. This will make it cover the viewport, ignoring the height of body
.min-height: 100%
to body
. This will make it be at least as tall as html
.html, body {
margin: 0;
padding: 0
}
html {
height: 100%;
}
body {
min-height: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.sheet {
width: 80%;
max-width: 1024px;
height: 400px;
background-color: red;
}
<div class="sheet"></div>
Upvotes: 4