1. How would you implement a three-column layout using flex, position, and float?
The full question
How would you implement a three-column layout using flex, position, and float? Share the code.
Model answer
Below is a complete JavaScript example that creates three separate three-column layouts: Flexbox, positioning, and floats. Each layout has a fixed-width left and right column with a flexible center column.
// Add the styles for all three layout techniques.
const style = document.createElement("style");
style.textContent = `
* { box-sizing: border-box; }
body { font-family: sans-serif; margin: 24px; }
.demo { margin: 0 0 32px; }
.row { min-height: 120px; }
.left, .right { width: 180px; padding: 16px; background: #e8eef8; }
.center { padding: 16px; background: #f4f4f4; }
/* Flexbox: the center column grows to fill available space. */
.flex-row { display: flex; }
.flex-row .center { flex: 1; }
/* Positioning: reserve space for the absolutely positioned side columns. */
.position-row { position: relative; padding: 0 180px; }
.position-row .left,
.position-row .right { position: absolute; top: 0; bottom: 0; }
.position-row .left { left: 0; }
.position-row .right { right: 0; }
/* Floats: the center occupies the space between the floated columns. */
.float-row::after { content: ""; display: block; clear: both; }
.float-row .left { float: left; }
.float-row .right { float: right; }
.float-row .center { overflow: hidden; }
@media (max-width: 640px) {
.flex-row { flex-direction: column; }
.flex-row .left, .flex-row .right { width: 100%; }
.position-row { padding: 0; }
.position-row .left, .position-row .right {
position: static; width: 100%;
}
.float-row .left, .float-row .right {
float: none; width: 100%;
}
}
`;
document.head.appendChild(style);
// Create the same three-column content for each layout demonstration.
function createDemo(title, layoutClass) {
const section = document.createElement("section");
section.className = "demo";
section.innerHTML = `
<h2>${title}</h2>
<div class="row ${layoutClass}">
<aside class="left">Left column</aside>
<main class="center">Center column</main>
<aside class="right">Right column</aside>
</div>
`;
document.body.appendChild(section);
}
createDemo("Flexbox", "flex-row");
createDemo("Positioning", "position-row");
createDemo("Floats", "float-row");
- Flexbox is the most straightforward modern choice for this layout;
flex: 1lets the center use remaining space. - Positioning takes the side columns out of normal flow, so the parent must reserve their width.
- Floats require clearing;
overflow: hiddenalso establishes a block formatting context for the center.