There are three main ways to arrange things on a webpage: Flexbox, Grid, and Float. This lesson shows you what each one does and when to use them.
Flexbox
Flexbox arranges items in a single line - either a row (left to right) or a column (top to bottom). It's great for spacing things out evenly and centering stuff.
.container {
display: flex;
justify-content: space-around; /* horizontal alignment */
align-items: center; /* vertical alignment */
gap: 10px; /* space between items */
flex-wrap: wrap; /* wrap to next line */
}
Demo
CSS Grid
Grid lets you create rows AND columns at the same time. Think of it like a table or a spreadsheet. You can place items exactly where you want them.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
grid-template-rows: repeat(2, 70px); /* 2 rows, 70px each */
gap: 10px;
}
.header {
grid-column: span 2; /* span across 2 columns */
}
Demo
Float (Old Method)
Float was made to wrap text around images, like in a newspaper. People used it for layouts before Flexbox and Grid existed. Now it's outdated for layouts - just use it for text wrapping.
.image {
float: left; /* or float: right */
margin-right: 15px;
}
.container {
overflow: hidden; /* clearfix hack */
}
Try it - Text wrapping around image
This text wraps around the box on the left. This is what float is actually for - making text flow around an image like in a magazine or newspaper. This is the only thing you should use float for nowadays.
Quick Comparison
| Feature | Flexbox | Grid | Float |
|---|---|---|---|
| Direction | One direction (row or column) | Both directions (rows and columns) | Just pushes left or right |
| Best For | Menus, buttons, centering | Full page layouts, galleries | Text around images only |
| Easy to Use | Yes | Yes | No, causes problems |
| Should You Use It? | Yes, use it | Yes, use it | Only for text wrapping |
When to Use What?
Not sure which one to pick? Here's a simple guide.
Use Flexbox For:
- Navigation menus
- Cards in a row
- Centering things
- Spacing items evenly
- Buttons side by side
Use Grid For:
- Whole page layouts
- Photo galleries
- Dashboard layouts
- Anything with rows AND columns
Use Float For:
- Text wrapping around images
- That's it. Nothing else.
Summary
- Flexbox - puts things in a row or column.
- Grid - creates rows and columns together.
- Float - old method, only use for text around images.
- Best practice - use Grid + Flexbox together for modern websites.