Flexbox is a powerful tool for creating responsive layouts in CSS. In this section, we will explore some common flexbox examples that can help you understand how to use flexbox in your projects.

Basic Flex Container

A flex container is an element that contains flex items. By default, flex containers use a horizontal layout, but you can easily change the direction with the flex-direction property.

Example

<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;
}

.flex-item {
  background-color: #f3f3f3;
  margin: 10px;
  padding: 20px;
}

In this example, the .flex-container is the flex container and the .flex-item is the flex item. The flex items will be displayed horizontally by default.

Flex Item Alignment

You can align flex items using various properties such as justify-content, align-items, and align-self.

Example

<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-around; /* Distribute space around items */
  align-items: center; /* Center items vertically */
}

In this example, the flex items are distributed evenly with space around them and centered vertically.

Flex Wrap

If you have more flex items than can fit in the container, you can enable flex wrap with the flex-wrap property.

Example

<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 class="flex-item">Item 4</div>
</div>
.flex-container {
  display: flex;
  flex-wrap: wrap; /* Enable wrapping */
}

In this example, the flex items will wrap onto the next line if there isn't enough space.

For more information and advanced examples, please visit our Flexbox Documentation.