Telz Telz - 3 months ago 13
CSS Question

How do I hide my sticky footer with a flexbox layout?

I'm trying to implement a simple layout using CSS flexboxes, but I'm stuck.

Here is what I am trying to do (pardon my paint skills):

large viewport
small viewport

Basically I'm trying to make the footer stick to the bottom of the viewport and the main content container fill the remaining space. If the viewport is too small, then the footer must not be visible but be accessed by scrolling down the page.

Here is my code (which does not work as intended):

<body>
<div class='layout-wrapper>
<div class='layout-main'>
<div class='content'>Content</div>
</div>
<footer>Footer</footer>
</div>
</body>

.layout-wrapper {
display: flex;
flex-direction: column;
}

.layout-main {
flex-grow: 1;
}


This makes the footer stick to the bottom if the viewport is large enough, but if the viewport is too small, it is the
layout-main
div that shrinks (hiding the content if I put a
overflow: hidden
on that div) instead of the footer just staying under the content.

Is there a way of doing what I'm trying to do using only CSS? I can use JavaScript but I'd rather go for a full CSS solution.

Answer

You should use height: 100vh on layout-wrapper and flex: 1 on main content container.

body,
html {
  margin: 0;
  padding: 0;
}
.layout-wrapper {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
footer {
  border: 2px solid red;
}
.layout-main {
  flex: 1;
  border: 2px solid blue;
}
.content {
  border: 2px solid orange;
  color: orange;
}
<div class='layout-wrapper'>
  <div class='layout-main'>
    <div class='content'>Content</div>
  </div>
  <footer>Footer</footer>
</div>