HTML & CSSEasy
What is Flexbox?
Flexbox (the Flexible Box Layout) is a one-dimensional layout model: a flex container (display: flex) arranges its direct children in a row or a column and controls how they are aligned, spaced, wrapped and how they grow or shrink to fill the space. It is the go-to tool for navbars, toolbars, centering and rows of cards.
Container properties
flex-direction:row(default),column, and their-reverseversions.justify-content: distribution along the main axis (flex-start,center,space-between…).align-items: alignment on the cross axis (stretchdefault,center,baseline…).flex-wrap: wrap: allow items onto new lines;align-contentspaces those lines.gap: spacing between items.
Item properties
flex: 1(shorthand for grow/shrink/basis): share free space.align-self: override cross-axis alignment for one item.order: change visual order (does not change tab or reading order, so use it carefully).margin-left: auto: pushes the item and everything after it to the end.
Classic one-liners
- Perfect centering:
display: flex; justify-content: center; align-items: center; - Sticky footer: a column flex body with
main { flex: 1 }. - Equal-height cards: the default
align-items: stretch.
Gotcha
Flex items have min-width: auto, so long words or wide children can overflow; add min-width: 0 to the item.
Interview tip
Flexbox is content-out (items size the layout); Grid is layout-in (the grid sizes the items). Use them together.
Code example
html
1<style>2 body { font-family: system-ui; margin: 0; }3 nav { display: flex; align-items: center; gap: 12px; padding: 10px 16px; background: #0b1020; color: white; }4 nav .push { margin-left: auto; } /* pushes the button to the right */5 .cards { display: flex; flex-wrap: wrap; gap: 12px; padding: 16px; }6 .card { flex: 1 1 160px; border: 2px solid #0b1020; padding: 12px; border-radius: 8px; }7 .center { display: flex; justify-content: center; align-items: center; height: 100px; background: #fef9c3; }8</style>9<nav>10 <strong>DevQnA</strong>11 <a href="#" style="color:white">Docs</a>12 <a href="#" style="color:white">Blog</a>13 <button class="push">Sign in</button>14</nav>15<div class="cards">16 <div class="card">Equal height cards that wrap</div>17 <div class="card">Second card with more text to show that all cards in a row stretch to the same height</div>18 <div class="card">Third</div>19</div>20<div class="center">Perfectly centered</div>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.