I am working on a layout using HTML and CSS with Flexbox. I want to ensure that the entire page takes up 100% height, with a header
, sidebar
, main-contents
, and footer
.
In my current implementation, the height is not properly set, causing the footer
not to stick to the bottom of the page and the sidebar
and main-contents
not to fill the available space.
Here is my current HTML and CSS code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html ,body{
margin:0;
height: 100vh;
}
.container{
flex-direction: column;
flex:1;
}
.header{
display:flex;
background-color: #333;
justify-content: center;
color:white;
padding: 20px;
align-items: center;
}
.main{
display:flex;
flex:1;
}
.sidebar{
display:flex;
flex-direction: column;
background-color: #f4f4f4;
padding: 20px;
flex-basis: 200px;
}
.title{
display:flex;
flex-direction: column;
border:1px solid white;
padding: 20px;
margin:20px;
flex:1;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
}
.main-contents{
display:flex;
flex-direction: column;
flex:1;
}
.footer{
display:flex;
background-color: #333;
justify-content: center;
color:white;
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>My Blog</h1>
</div>
<div class="main">
<div class="sidebar">
<h2>About me</h2>
<P>Some information about me.</P>
<h2>Categories</h2>
<ul>
<li>Category 1</li>
<li>Category 2</li>
<li>Category 3</li>
</ul>
</div>
<div class="main-contents">
<div class=title>
<h2>Post Title 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vel tortor facilisis, aliquet lacus a, pharetra quam.</p>
</div>
<div class="title">
<h2>Post Title 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vel tortor facilisis, aliquet lacus a, pharetra quam.</p>
</div>
<div class="title">
<h2>Post Title 3</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vel tortor facilisis, aliquet lacus a, pharetra quam.</p>
</div>
</div>
</div>
<div class="footer">
<p>Footer Content</p>
</div>
</div>
</body>
</html>
What I Tried and Expected Results
I have tried the following approaches:
- Setting html and body height to 100%.
- Using min-height: 100vh; on the .container to ensure it takes up the full viewport height.
- Setting flex: 1; on the .main to ensure it expands to fill the remaining space.
- Applying flex-direction: column; on the .main-contents to make it take up the available vertical space.
Despite these efforts, the footer does not stick to the bottom of the page as expected, and the sidebar and main-contents do not fill the remaining space properly.
2
Answers
You should change your css code a little like this:
You forgot to add
.container{ display:flex; }
.Also don’t set a hard height to
body
, betterbody{ min-height: 100dvh; }
: