DEV Community

Lokesh
Lokesh

Posted on

CSS Flexbox

What Is CSS Flexbox?

Flexbox stands for Flexible Box Layout.

It is used to arrange elements in a row or column and control their alignment and spacing.

For example, if we want to display three boxes next to each other, Flexbox makes it easy.

How to Use Flexbox?

To use Flexbox, we need to apply display: flex to a parent element.

HTML:

<div class="container">
    <div>Box 1</div>
    <div>Box 2</div>
    <div>Box 3</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.container {
    display: flex;
    gap: 10px;
}
Enter fullscreen mode Exit fullscreen mode

Here, display: flex arranges the boxes in a row by default, and gap adds space between them.

Important Flexbox Properties

1. display: flex

This property enables Flexbox for the child elements of a container.

.container {
    display: flex;
}
Enter fullscreen mode Exit fullscreen mode

2. flex-direction

It controls the direction in which the elements are arranged.

.container {
    display: flex;
    flex-direction: row;
}
Enter fullscreen mode Exit fullscreen mode
  • row arranges elements horizontally.
  • column arranges elements vertically.
  • row-reverse reverses the horizontal order.
  • column-reverse reverses the vertical order.

3. justify-content

It controls the alignment of elements along the main axis.

.container {
    display: flex;
    justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

Some commonly used values are:

  • flex-start — places items at the start.
  • center — places items at the center.
  • flex-end — places items at the end.
  • space-between — places space between items.
  • space-around — adds space around items.
  • space-evenly — distributes space evenly.

4. align-items

It controls the alignment of items along the cross axis.

.container {
    display: flex;
    align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

For example, when flex-direction is row, align-items: center vertically centers the items within the container.

5. gap

The gap property adds space between items.

.container {
    display: flex;
    gap: 20px;
}
Enter fullscreen mode Exit fullscreen mode

This creates a 20px gap between the items.

Where Is Flexbox Used?

Flexbox is commonly used to create:

  • Navigation bars
  • Buttons arranged in a row
  • Card layouts
  • Centered content
  • Headers and footers

It helps us organize webpage elements without manually adjusting their positions.

Top comments (0)