CSS

Vertically Aligning Header/Footer in a Flex Component

Use Flexbox to efficiently arrange a component's header and footer at opposite ends, with main content dynamically fitting in between, perfect for card-like layouts.

.card-component {
  display: flex;
  flex-direction: column; /* Stack items vertically */
  justify-content: space-between; /* Pushes first and last item to ends */
  height: 250px; /* Fixed height for demonstration */
  width: 200px;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
  margin: 1rem;
  background-color: white;
}

.card-header,
.card-footer {
  background-color: #f8f8f8;
  padding: 0.8rem;
  font-weight: bold;
  text-align: center;
  flex-shrink: 0; /* Prevent header/footer from shrinking */
}

.card-content {
  flex-grow: 1; /* Allows content to take up remaining space */
  padding: 0.8rem;
  text-align: center;
  color: #555;
  overflow-y: auto; /* Scroll content if it overflows */
}


<div class="card-component">
  <div class="card-header">Card Title</div>
  <div class="card-content">
    <p>This is the main content area of the card. It will dynamically grow to fill the available space between the header and footer.</p>
    <p>More content can be added here.</p>
  </div>
  <div class="card-footer">Action Buttons</div>
</div>

<div class="card-component">
    <div class="card-header">Another Card</div>
    <div class="card-content">
        <p>Shorter content for this card.</p>
    </div>
    <div class="card-footer">Details Link</div>
</div>
How it works: This snippet demonstrates how to use Flexbox to create a component with a header, content, and footer, where the header and footer are pushed to the top and bottom edges, and the content fills the remaining vertical space. By setting `display: flex` and `flex-direction: column` on the container, and `justify-content: space-between`, the first and last child elements are separated. The `flex-grow: 1` on the content area ensures it expands to occupy all available vertical space in between. This pattern is highly useful for card-like components, modals, or any fixed-height container needing distinct top/bottom sections.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs