CSS

Flexbox Holy Grail Layout with `order` Property

Create a classic responsive 'Holy Grail' layout (header, main, sidebar, footer) using Flexbox, demonstrating the `order` property for source code independence.

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh; /* Optional: for full viewport height */
}

.header, .footer {
  flex-shrink: 0; /* Prevents header/footer from shrinking */
}

.main-content {
  display: flex;
  flex-grow: 1; /* Allows main content to take remaining space */
  flex-direction: column; /* For stacking main and sidebar vertically on small screens */
}

.sidebar {
  flex-basis: 200px; /* Default width */
  flex-shrink: 0; /* Prevents sidebar from shrinking */
  order: 3; /* Places sidebar after main on desktop, or adjusts on mobile */
  background-color: #f0f0f0;
  padding: 15px;
}

.main {
  flex-grow: 1; /* Allows main to take remaining space within main-content */
  order: 2; /* Main content before sidebar on desktop */
  background-color: #ffffff;
  padding: 15px;
}

@media (min-width: 768px) {
  .main-content {
    flex-direction: row; /* Desktop: main and sidebar side-by-side */
  }
  .sidebar {
    order: unset; /* Reset order for desktop if sidebar is on the right */
    /* To place sidebar on the right, ensure its order is higher than main, or set main to 1, sidebar to 2 etc. */
    /* For a left sidebar: .main { order: 2; } .sidebar { order: 1; } */
  }
}
How it works: This snippet crafts a responsive 'Holy Grail' layout using Flexbox. The outer container stacks header, main-content, and footer vertically. The `main-content` then uses Flexbox to arrange `main` and `sidebar` horizontally on larger screens, stacking them vertically on smaller ones. The `order` property demonstrates how to visually reorder elements independent of their HTML source order, allowing for flexible layout adjustments across different screen sizes. `flex-grow` ensures main content fills available space, while `flex-shrink: 0` prevents header/footer from shrinking.

Need help integrating this into your project?

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

Hire DigitalCodeLabs