Skip to main content

Command Palette

Search for a command to run...

A Beginner's Guide to Flexbox

Published
2 min read
A Beginner's Guide to Flexbox

Flexbox is a powerful and flexible CSS layout system that allows you to create responsive and dynamic layouts with ease.


What is Flexbox?

Flexbox allows you to control the layout of items inside a container, making it ideal for building responsive designs. To enable Flexbox, set the container's display property to flex


.flex-container {
  display: flex;
}

Basic Flexbox Properties

1. Flex Direction

The flex-direction property determines the direction of the items inside the flex container. Options are:

  • row (default)

  • column

      .flex-container {
        display: flex;
        flex-direction: column;
      }
      .flex-item {
        padding: 20px;
        background-color: #add8e6;
        }
    

2. Justify Content

This property controls how items are spaced along the main axis (horizontal by default). Options:

  • flex-start, center, space-between, space-around
.flex-container {
  display: flex;
  justify-content: center;
}
.flex-item {
  padding: 20px;
  background-color: #add8e6;
  }

3. Align Items

Aligns items along the cross axis (vertical by default). Options:

  • flex-start, center, stretch

.flex-container {
  display: flex;
  align-items: center;
}
.flex-item {
  padding: 20px;
  background-color: #add8e6;
}

4. Flex Wrap

By default, items will stay in one line. To allow items to wrap to the next line:


.flex-container {
  display: flex;
  flex-wrap: wrap;
  margin: 2px;
}
.flex-item {
  padding: 20px;
  background-color: #add8e6;
  }


Example: Simple Flexbox Layout


<div class="flex-container">
  <div class="flex-item">Item 1</div>
  <div class="flex-item">Item 2</div>
  <div class="flex-item">Item 3</div>
</div>

.flex-container {
  display: flex;
  justify-content: space-between;
}

.flex-item {
  padding: 50px;
  background-color: lightblue;
}

  • Flexbox Layout: The code creates a Flexbox layout with three items inside a flex container.

  • display: flex: The container uses display: flex to enable Flexbox, making its child elements behave as flex items.

  • justify-content: space-between: This property spaces the items evenly along the horizontal axis, with no space at the start or end.


Flexbox is a simple yet powerful tool to create flexible layouts. By mastering properties like flex-direction, justify-content, and align-items, you can build responsive designs quickly.

Happy Coding! 😊