DEV Community

Cover image for FLEXBOX
Rakshambika
Rakshambika

Posted on

FLEXBOX

What is Flexbox?

Flexbox (Flexible Box Layout) is a one-dimensional layout model designed to arrange items in rows or columns.

It helps developers:

  • Align items horizontally and vertically
  • Create responsive layouts
  • Distribute space efficiently
  • Build navigation bars, cards, galleries, and more
  • Basic Flexbox Structure

HTML

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

CSS

.container {
    display: flex;
}

Enter fullscreen mode Exit fullscreen mode

Once display: flex is applied:

The parent becomes a Flex Container
The child elements become Flex Items

By default, the items are displayed in a row.

Main Axis vs Cross Axis

Understanding these two axes is essential when working with Flexbox.

Main Axis

The direction in which flex items are placed.

Default:

flex-direction: row;

Main Axis → Horizontal

Cross Axis

The axis perpendicular to the main axis.

Cross Axis → Vertical

Most Flexbox properties work based on these two axes.

flex-direction

The flex-direction property determines the direction of flex items.

Syntax

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

Available Values
row (Default)

flex-direction: row;

Output:
1 2 3

column

flex-direction: column;

Output:
1
2
3

justify-content

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

Syntax

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

Common Values
flex-start

justify-content: flex-start;

Items appear at the beginning.

flex-end

justify-content: flex-end;

Items appear at the end.

center
justify-content: center;
Items appear in the center.

space-between
justify-content: space-between;

Equal space between items.

space-around
justify-content: space-around;

Equal space around items.

space-evenly
justify-content: space-evenly;

Equal spacing throughout the container.

align-items

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

Syntax

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

Common Values
stretch (Default)
align-items: stretch;

Items stretch to fill the container height.

flex-start
align-items: flex-start;

Items align to the top.

flex-end
align-items: flex-end;

Items align to the bottom.

center
align-items: center;

Items align vertically in the center.

flex-wrap

By default, flex items stay on a single line.

Example

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

Values
flex-wrap: nowrap;

Single line only.

flex-wrap: wrap;

Items move to the next line if needed.

flex-wrap: wrap-reverse;

Items wrap in reverse order.

Top comments (0)