Creating a Flexbox Layout Using CSS

The flexbox is another layout model in CSS that provides an efficient way to design and structure complex layouts, but with a more flexible approach. It is particularly suited for creating one-dimensional layouts, either in a row or a column, as we will see later.

Just like a grid layout, a flexbox layout also consists of a flex container and several flex items. The container should have its display property set to flex, and all of its direct children automatically become flex items.

html
1<div class="container">
2  <div class="item">1</div>
3  <div class="item">2</div>
4  <div class="item">3</div>
5  <div class="item">4</div>
6  <div class="item">5</div>
7  <div class="item">6</div>
8</div>
css
1.container {
2  display: flex;
3  gap: 10px;
4}

Flex direction

With a flex layout, instead of rows and columns, you must define a flex-direction and a flex-wrap. The flex-direction specifies in which direction the container should stack its flex items. The accepted values are:

  • column
css
1.container {
2  flex-direction: column;
3}

flex direction column

  • column-reverse
css
1.container {
2  flex-direction: column-reverse;
3}

flex direction column reverse

  • row
css
1.container {
2  flex-direction: row;
3}

flex direction row

  • row-reverse
css
1.container {
2  flex-direction: row-reverse;
3}

flex direction row reverse

Flex wrap

The flex-wrap property determines whether the flex items should wrap, which means automatically change to the following line when there is insufficient space.

  • wrap
css
1.container {
2  flex-wrap: wrap;
3}

flex wrap

  • nowrap
css
1.container {
2  flex-wrap: nowrap;
3}

flex nowrap

  • wrap-reverse
css
1.container {
2  flex-wrap: wrap-reverse;
3}

flex wrap reverse

The flex-flow is a shorthand for both flex-direction and flex-wrap properties.

css
1.container {
2  flex-flow: column wrap;
3}

flex flow