0
0
CssHow-ToBeginner · 3 min read

How to Create a Flex Container in CSS: Simple Guide

To create a flex container in CSS, set the display property of a container element to flex. This makes its direct children flexible items that can be arranged easily in rows or columns.
📐

Syntax

Use the display: flex; property on a container element to make it a flex container. This changes how its child elements behave, allowing flexible layouts.

  • display: CSS property to define the display behavior.
  • flex: Value that turns the container into a flex container.
css
selector {
  display: flex;
}
💻

Example

This example shows a container with three boxes arranged in a row using flexbox. The container uses display: flex; to align its children horizontally.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flex Container Example</title>
<style>
  .flex-container {
    display: flex;
    gap: 1rem;
    background-color: #f0f0f0;
    padding: 1rem;
  }
  .box {
    background-color: #4CAF50;
    color: white;
    padding: 1rem;
    border-radius: 0.5rem;
    flex: 1;
    text-align: center;
  }
</style>
</head>
<body>
  <section class="flex-container">
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
    <div class="box">Box 3</div>
  </section>
</body>
</html>
Output
A horizontal row of three green boxes labeled 'Box 1', 'Box 2', and 'Box 3' spaced evenly inside a light gray container.
⚠️

Common Pitfalls

Common mistakes when creating a flex container include:

  • Forgetting to set display: flex; on the container, so children stay in normal block or inline layout.
  • Applying flex properties to child elements without a flex container parent.
  • Not understanding that only direct children become flex items.

Here is an example showing the wrong and right way:

css
/* Wrong: flex properties on children without flex container */
.container {
  /* missing display: flex; */
}
.child {
  flex: 1;
}

/* Right: flex container with flex children */
.container {
  display: flex;
}
.child {
  flex: 1;
}
📊

Quick Reference

Remember these key points when creating a flex container:

  • display: flex; makes the container flexible.
  • Only direct children become flex items.
  • Use flex-direction to change row/column layout.
  • Use gap to add space between items.

Key Takeaways

Set display: flex; on a container to create a flex container.
Only direct children of the flex container become flexible items.
Use flex-direction and gap to control layout and spacing.
Without display: flex;, flex properties on children have no effect.
Flexbox helps arrange items easily in rows or columns with flexible sizing.