CSS Flexbox Layout

What is CSS Flexbox?

CSS Flexbox is a layout model that allows you to create flexible and efficient layouts. It provides a way to arrange items within a container, helping you control alignment, spacing, and the overall design. Flexbox is especially useful for creating responsive, one-dimensional layouts (either row or column based).

Key Concepts of Flexbox

1. Flex Container and Flex Items

2. Enabling Flexbox

To use Flexbox, you simply set the display property of the parent container to flex:

.container {
  display: flex;
}

Image References

Main and Cross Axis

Main Flexbox Properties

1. Flex Direction

The flex-direction property defines how the flex items are laid out inside the flex container.

Example:

.container {
  flex-direction: row;
}

2. Justify Content

The justify-content property aligns the flex items along the main axis (the primary axis set by flex-direction).

Options:

Example:

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

3. Align Items

The align-items property controls how flex items are aligned along the cross axis (the opposite axis of the main axis).

Options:

Example:

.container {
  align-items: center;
}

4. Flex Wrap

The flex-wrap property specifies whether flex items should wrap onto multiple lines if they don’t fit in a single row or column.

Options:

Example:

.container {
  flex-wrap: wrap;
}

5. Align Content

The align-content property aligns the flex lines when there’s extra space along the cross axis (only applies when flex-wrap is used).

Options:

Example:

.container {
  align-content: space-between;
}

6. Flex Grow, Flex Shrink, and Flex Basis

These properties allow you to control how flex items grow and shrink relative to each other and define their initial size.

Using Flexbox in Real Scenarios

Flexbox is great for building responsive, one-dimensional layouts where elements need to align and space themselves properly. It’s particularly useful when creating flexible components such as navigation bars, card layouts, or grid-based systems where items need to adjust their size based on available space.

Example: Creating a Simple Flexbox Layout

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>
.container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 200px;
}
.item {
  flex-grow: 1;
  padding: 10px;
}

Summary

Summary

Practical Exercise for Students

  1. Create a Responsive Header: Build a navigation bar with Flexbox that has evenly spaced links and adjusts based on screen width. Ensure the content is centered both vertically and horizontally.
  2. Build a Pricing Table: Use Flexbox to create a three-column pricing table. Each column should contain pricing information, and all columns should be evenly spaced and centered on the page.

This exercise will reinforce the concepts of Flexbox and when to apply the position property effectively.