CSS Flexbox

1. Introduction to CSS Flexbox

CSS Flexbox (Flexible Box Layout) is a layout model designed to provide a more efficient way to arrange, align, and distribute space among items in a container, even when their size is unknown or dynamic.

Flexbox is ideal for:

Flexbox consists of two main components:

  1. Flex Container: The parent element that holds flex items.
  2. Flex Items: The child elements inside the flex container.

2. Flex Container

To create a flex container, set the display property to flex or inline-flex.

.container {
  display: flex; /* Creates a flex container */
}

Key properties for the flex container:


3. Flex Direction

The flex-direction property defines the direction in which flex items are placed in the container.

.container {
  flex-direction: row; /* Default: left to right */
  flex-direction: row-reverse; /* Right to left */
  flex-direction: column; /* Top to bottom */
  flex-direction: column-reverse; /* Bottom to top */
}

4. Justify Content

The justify-content property aligns items along the main axis.

.container {
  justify-content: flex-start; /* Default: items at the start */
  justify-content: flex-end; /* Items at the end */
  justify-content: center; /* Items centered */
  justify-content: space-between; /* Items evenly spaced */
  justify-content: space-around; /* Items spaced with equal space around them */
  justify-content: space-evenly; /* Items evenly distributed */
}

5. Align Items

The align-items property aligns items along the cross axis.

.container {
  align-items: stretch; /* Default: items stretch to fill the container */
  align-items: flex-start; /* Items aligned to the start */
  align-items: flex-end; /* Items aligned to the end */
  align-items: center; /* Items centered */
  align-items: baseline; /* Items aligned to their baselines */
}

6. Flex Wrap

The flex-wrap property controls whether items wrap to the next line when they exceed the container's width.

.container {
  flex-wrap: nowrap; /* Default: items stay in one line */
  flex-wrap: wrap; /* Items wrap to the next line */
  flex-wrap: wrap-reverse; /* Items wrap in reverse order */
}