Flexbox Architecture
Overview
Before 2010, developers had to use catastrophic hacks like float: left; or HTML <table>s to put two elements side-by-side. Flexbox (Flexible Box Layout) changed the world. Flexbox is a 1-Dimensional layout system. It is designed to distribute space and align items along a SINGLE straight line (either a horizontal row OR a vertical column). It consists of two components: The 'Flex Container' (the parent that holds the power) and the 'Flex Items' (the children that are manipulated).
Syntax
/* 1. The Flex Container (The Parent) */
.container {
/* This single line instantly activates the Flexbox engine! */
display: flex;
/* All direct children instantly sit side-by-side in a row */
}
/* 2. The Flex Items (The Children) */
.item {
/* You can optionally give instructions to individual children */
flex: 1; /* Tells the child to grow and fill empty space */
}Common Pitfalls
- Assuming Flexbox applies to grandchildren.
display: flex;ONLY affects the DIRECT children of the container. If you have a<div>inside a flex container, and an<img />inside that div, the image is completely unaffected by the Flexbox rules. - Trying to use Flexbox for complex, 2D newspaper-style grids (Rows AND Columns simultaneously). While you can hack Flexbox to wrap and look like a grid, it is strictly 1-dimensional. For true 2D layouts, you should use CSS Grid.
Interview Questions
margin-collapse bug when an element is placed inside a Flex container?Margin collapse is completely disabled. Flexbox explicitly honors exact margin math, making spacing vastly more predictable.
Real-World Example
The classic 'Centering a Div' meme, solved flawlessly in 3 lines of CSS.
.hero-section {
display: flex;
/* Centers on the Main Axis (Horizontal) */
justify-content: center;
/* Centers on the Cross Axis (Vertical) */
align-items: center;
height: 100vh; /* Needs physical height to center vertically! */
}Check Your Knowledge
Test your understanding of Flexbox Architecture with these quick questions.