HTML/CSS - 13

HTML/CSS - 13: Flexbox Fundamentals

Flexbox is a CSS layout system that makes it much easier to arrange elements in rows or columns and control the space between them.

To start using Flexbox, you add display: flex; to a container. The elements directly inside that container then become flex items.

You can control the layout with properties such as justify-content, align-items, flex-direction, and gap.

Your challenge: Arrange three boxes with Flexbox, then experiment with their direction, spacing, and alignment.

✦ HTML Editor
▶ Live Output

What should you notice?

Before Flexbox is added, normal <div> elements usually appear one below another. When the parent container gets display: flex;, its direct children are arranged in a row by default.

The container is called the flex container, and the boxes inside it are called flex items. Most of the layout controls are added to the container.

Experiment with gap: Try gap: 5px;, then gap: 40px;. The boxes stay separate, but the amount of space between them changes.

Experiment with flex-direction: Add flex-direction: column;. The boxes should move from a horizontal row into a vertical column. Change it back to row when you are finished.

Try justify-content: Remove flex: 1; from the boxes temporarily, then try justify-content: center;, justify-content: space-between;, and justify-content: space-around;.

This makes the differences easier to see because the boxes are no longer stretching to fill all available space.

Try align-items: Give the container min-height: 200px;, then add align-items: center;. The boxes should move toward the middle of the container vertically when using the default row direction.

Good Flexbox habit: Remember that display: flex; belongs on the parent container. It controls the arrangement of the elements directly inside it.

👀 Show Solution
<style>

  .flex-container {
    display: flex;
    gap: 15px;
    justify-content: space-between;
    align-items: center;
  }

  .box {
    background-color: #111;
    border: 2px solid #8A8A8A;
    padding: 20px;
    border-radius: 6px;
    text-align: center;
    flex: 1;
  }

</style>

<div class="flex-container">

  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>

</div>

The .flex-container becomes the flex container because it uses display: flex;. The three .box elements become flex items because they are directly inside it.

The gap property adds space between the boxes, while justify-content and align-items control their alignment. The flex: 1; rule tells each box to share the available space.