How to Create a Three Column Layout with Flexbox in CSS
Use a container with
display: flex; and add three child elements inside it. Set flex: 1; on each child to make them evenly share the space, creating a three column layout.Syntax
To create a three column layout with Flexbox, you need a container with display: flex;. Inside this container, place three child elements. Use flex: 1; on each child to make them take equal width.
display: flex;: activates flexbox layout on the container.flex: 1;: makes each child grow equally to fill the container.
css
/* Container setup */ .container { display: flex; } /* Each column setup */ .column { flex: 1; padding: 1rem; border: 1px solid #ccc; }
Example
This example shows a container with three columns side by side. Each column shares equal width and has padding and border for clarity.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Three Column Flexbox Layout</title> <style> .container { display: flex; gap: 1rem; } .column { flex: 1; padding: 1rem; border: 1px solid #ccc; background-color: #f9f9f9; text-align: center; } </style> </head> <body> <div class="container"> <div class="column">Column 1</div> <div class="column">Column 2</div> <div class="column">Column 3</div> </div> </body> </html>
Output
A webpage showing three equal columns side by side with light gray backgrounds and borders, each labeled 'Column 1', 'Column 2', and 'Column 3'.
Common Pitfalls
Common mistakes include:
- Not setting
display: flex;on the container, so children stack vertically. - Forgetting to set
flex: 1;on children, causing columns to shrink to content size. - Not adding
gapor margins, making columns stick together without space.
Always check your container and children styles carefully.
css
/* Wrong: Missing display flex */ .container { /* display: flex; */ } .column { flex: 1; } /* Right: Correct flex container */ .container { display: flex; } .column { flex: 1; }
Quick Reference
| Property | Description | Example Value |
|---|---|---|
| display | Defines flex container | flex |
| flex | Defines how child grows/shrinks | 1 |
| gap | Space between flex items | 1rem |
| padding | Inner space inside columns | 1rem |
| border | Visual boundary of columns | 1px solid #ccc |
Key Takeaways
Set
display: flex; on the container to enable flexbox layout.Use
flex: 1; on each child to make columns equal width.Add
gap or margins for spacing between columns.Without
display: flex;, columns stack vertically by default.Flexbox makes responsive layouts easy and flexible.