0
0
CSSmarkup~5 mins

Flex container in CSS

Choose your learning style9 modes available
Introduction

A flex container helps arrange items in a row or column easily. It makes layouts flexible and neat without complicated code.

You want to line up buttons horizontally with equal spacing.
You need a navigation menu that adjusts on small screens.
You want to center content both vertically and horizontally.
You want items to wrap to the next line when the screen is small.
You want to create a simple responsive card layout.
Syntax
CSS
selector {
  display: flex;
}

Use display: flex; on a container to make it a flex container.

All direct children of this container become flex items.

Examples
This makes the nav element a flex container, so its child links line up in a row by default.
CSS
nav {
  display: flex;
}
This makes the container stack its children vertically instead of horizontally.
CSS
.container {
  display: flex;
  flex-direction: column;
}
This centers the flex items horizontally and vertically inside the container.
CSS
.box {
  display: flex;
  justify-content: center;
  align-items: center;
}
Sample Program

This example creates a flex container with three items. They appear side by side with space between them. On small screens, they stack vertically. The container and items have colors and padding for clarity.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Flex Container Example</title>
  <style>
    .flex-container {
      display: flex;
      gap: 1rem;
      background-color: #f0f0f0;
      padding: 1rem;
      border: 2px solid #ccc;
    }
    .flex-item {
      background-color: #4caf50;
      color: white;
      padding: 1rem 2rem;
      border-radius: 0.5rem;
      font-weight: bold;
      flex: 1;
      text-align: center;
    }
    @media (max-width: 600px) {
      .flex-container {
        flex-direction: column;
      }
    }
  </style>
</head>
<body>
  <section class="flex-container" aria-label="Example flex container">
    <div class="flex-item">Item 1</div>
    <div class="flex-item">Item 2</div>
    <div class="flex-item">Item 3</div>
  </section>
</body>
</html>
OutputSuccess
Important Notes

Flex containers only affect their direct children, not nested elements inside those children.

Use browser DevTools to see the flex container and items highlighted and experiment with properties live.

Flexbox works well for one-dimensional layouts (row or column), not complex grids.

Summary

Flex container arranges child items in a row or column easily.

Set display: flex; on a container to start using flexbox.

Flexbox helps create responsive and neat layouts with little code.