0
0
CssHow-ToBeginner · 3 min read

How to Create Equal Width Columns with Flexbox in CSS

To create equal width columns with flexbox, set the container's display to flex and give each child element a flex: 1 style. This makes all columns share the available space equally regardless of their content.
📐

Syntax

Use display: flex; on the container to enable flexbox layout. Then, apply flex: 1; to each child element to make them grow equally and share the container's width evenly.

  • display: flex; - activates flexbox on the container.
  • flex: 1; - makes each child take equal share of space.
css
.container {
  display: flex;
}

.column {
  flex: 1;
}
💻

Example

This example shows a container with three equal width columns. Each column has a background color and some text to visualize the equal widths.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Equal Width Columns Flexbox</title>
<style>
  .container {
    display: flex;
    gap: 1rem;
    padding: 1rem;
  }
  .column {
    flex: 1;
    background-color: #4CAF50;
    color: white;
    padding: 1rem;
    text-align: center;
    border-radius: 0.5rem;
  }
</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 horizontal row with three equally wide green columns labeled 'Column 1', 'Column 2', and 'Column 3'. Each column has white centered text and some spacing between them.
⚠️

Common Pitfalls

One common mistake is forgetting to set flex: 1; on the child elements, which causes columns to size based on their content instead of equally. Another is not using display: flex; on the container, so flexbox layout does not activate.

Also, adding fixed widths or margins incorrectly can break equal sizing.

css
.container {
  display: flex;
}

/* Wrong: missing flex on children */
.column {
  /* no flex property here */
  background-color: lightblue;
}

/* Correct: equal width columns */
.column {
  flex: 1;
  background-color: lightblue;
}
📊

Quick Reference

  • Container: display: flex;
  • Columns: flex: 1; for equal width
  • Spacing: use gap on container for space between columns
  • Responsive: flexbox adapts columns to container width

Key Takeaways

Set the container's display to flex to enable flexbox layout.
Apply flex: 1 to each child to make columns share space equally.
Use gap on the container for consistent spacing between columns.
Avoid fixed widths on columns to keep them equal and flexible.
Flexbox automatically adjusts columns for responsive designs.