Understanding CSS Flexbox
What Flexbox Solves
Before Flexbox, centering things or distributing space evenly in CSS required awkward hacks. Flexbox gives you a one-dimensional layout system built for exactly that.
Setting Up a Flex Container
.container { display: flex; } Every direct child of a flex container automatically becomes a flex item, arranged in a row by default.
Main Axis Alignment
.container { display: flex; justify-content: space-between; /* start | center | space-between | space-around */ align-items: center; /* aligns items on the cross axis */ } Changing Direction
.container { flex-direction: column; /* stack vertically instead */ } Controlling Individual Items
.item { flex-grow: 1; /* how much it grows to fill space */ flex-shrink: 1; /* how much it shrinks if needed */ flex-basis: 200px; /* starting size before growing/shrinking */ } /* shorthand */ .item { flex: 1 1 200px; } A Practical Example: Navbar
.navbar { display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; } This single rule set handles logo-left, links-right, vertically centered — no floats, no manual positioning.
Flexbox vs. Grid
Use Flexbox for one-dimensional layouts (a row or a column, like a navbar or a card’s internal layout). Use CSS Grid when you need to control rows and columns together, like a full page layout.
Practice Exercise
Build a card with an image on the left and text content on the right using Flexbox, then make it stack vertically on small screens with a media query.

Leave a Reply