I tried to divide the body into three parts with different sizes, HEADER, CONTAINER, and FOOTER.
Header with 10% of the height, a container with 70% of the height, and a footer with 20%.
I tried to complete this task with flex but I can’t do it with percentages.
Please help.
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
background-color: skyblue;
width: 100%;
height: 100%;
display: flex;
flex-wrap: wrap;
flex-direction: column;
justify-content: center;
align-items: center;
align-content: space-between;
}
.header {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
background-color: black;
color: rgb(225, 150, 0);
font-weight: bold;
font-style: italic;
height: 10%;
padding: 5px 10px;
border: 1px solid blue;
}
.container {
width: 100%;
height: 70%;
border: 1px solid red;
}
.footer {
width: 100%;
height: 20%;
border: 1px solid green;
}
<div class="header">
<p>HEADER</p>
</div>
<div class="container">
<p>CONTAINER</p>
</div>
<div class="footer">
<p>FOOTER</p>
</div>
3
Answers
To achieve this use the CSS flex property with the values flex-base and flex-growth. See the code snippet down below
You can modify your code with the
flex property
to achieve your desired output.In extra, I have added
flex-shrink: 0;
to prevent the header and footer from shrinking when the viewport width is reduced.There are two ways of achieving this, with grid and flex; first, with grid:
JS Fiddle demo.
And, second, using flex:
JS Fiddle demo.
I feel it’s worth pointing out that – despite your stated requirements – you don’t really want to use those sizes as declared. A layout in which the elements are sized according to percentage can be great, but it also exposes the possibility of the content being displayed at the extremes, from ridiculously small (phones, watches) to ridiculously large (large screen displays).
With that said, I’d like to offer a slight revision of the above, taking advantage of the
clamp()
function; this allows us to set a "preferred" size, but with a specified minimum, and maximum:JS Fiddle demo.
And, second, using flex:
JS Fiddle demo.
References:
clamp()
.display
.flex-basis
.flex-grow
.gap
.grid-template-rows
.