CSSFlexbox Introduction

Flexbox Introduction

Flexbox is a CSS layout mode that makes it easy to arrange elements in a flexible, responsive way. It's ideal for one-dimensional layouts like navigation, toolbars, and single-row/column arrangements. The container distributes space and alignment to children automatically.

Flexbox Concepts

Concept

Description

Example

Flex container

Parent with display: flex

Navigation bar

Flex items

Direct children of container

Nav links

Main axis

Primary direction (horizontal)

Left to right

Cross axis

Perpendicular direction

Top to bottom

CSS
/* Enable flexbox */
.container {
  display: flex;
  /* Children become flex items */
}

/* Basic flex container */
.navbar {
  display: flex;
  gap: 20px;
  align-items: center;
  padding: 15px;
}

.navbar a {
  /* Becomes flex item */
  padding: 10px 15px;
}

/* Column layout */
.sidebar {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
Main Flex Properties

Property

Purpose

Example

display: flex

Enable flexbox

display: flex

flex-direction

Main axis direction

flex-direction: row

justify-content

Main axis alignment

justify-content: center

align-items

Cross axis alignment

align-items: center

gap

Space between items

gap: 20px

Common Flex Layouts

CSS
/* Horizontal navigation */
nav {
  display: flex;
  gap: 20px;
  padding: 15px;
  background: #333;
}

nav a {
  color: white;
  padding: 10px 15px;
  text-decoration: none;
}

/* Vertical sidebar */
.sidebar {
  display: flex;
  flex-direction: column;
  width: 250px;
  gap: 10px;
}

/* Centered container */
.hero {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400px;
  background: linear-gradient(to right, blue, purple);
  color: white;
}

/* Space-between layout */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
}
Note
Flexbox simplifies one-dimensional layouts. Set display: flex on container, items arrange automatically. Use gap for spacing, justify-content for main axis, align-items for cross axis.
Next
Flex direction: [flex-direction & flex-wrap](/css/flex-direction).