How to Fill the Space Between Header and Footer with Divs Using Flexbox?

Linda Hamilton
Release: 2024-11-19 06:10:03
Original
640 people have browsed it

How to Fill the Space Between Header and Footer with Divs Using Flexbox?

Filling Space Between Header and Footer with Divs

When transitioning from tables to divs for layout, a common challenge is accommodating dynamic content heights while maintaining the desired arrangement. Here's how to create a div that fills the entire space between a fixed header and footer.

Flexbox Solution

Flex layout provides an elegant solution for this scenario, allowing the container elements (header and footer) to adhere to their fixed heights while enabling the content area to adjust automatically. This setup resembles the default behavior of mobile apps.

HTML

<body>
  <header>
    ...
  </header>
  <main>
    ...
  </main>
  <footer>
    ...
  </footer>
</body>  
Copy after login

CSS

html, body {
  margin: 0;
  height: 100%;
  min-height: 100%;
}

body {
  display: flex;
  flex-direction: column;
}

header,
footer {
  flex: none;
}

main {
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  flex: auto;
}
Copy after login

In this setup, the body div becomes a flex container, and its child elements (header, main, and footer) become flex items. The flex-direction property specifies the direction of the flex items, in this case, vertically (column).

The header and footer elements are set to flex: none, meaning they won't shrink or grow relative to their initial dimensions, ensuring they retain their fixed heights. The main element, on the other hand, is set to flex: auto, indicating that it should fill the remaining space.

Additionally, overflow-y: scroll is applied to the main element to introduce vertical scrolling when the content surpasses the available space. The -webkit-overflow-scrolling: touch property improves scrolling behavior on iOS devices.

This setup effectively creates a flexible and dynamic layout where the header and footer remain fixed at their respective top and bottom positions, while the content div seamlessly fills the space in between them, accommodating varying screen heights.

The above is the detailed content of How to Fill the Space Between Header and Footer with Divs Using Flexbox?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template