CSS3 Flexible Box Layouts (Flexbox)

By Codes With Pankaj


CSS3 Flexible Box Layout, commonly known as Flexbox, is a powerful layout module that provides an efficient way to align and distribute space among items in a container, even when their size is unknown or dynamic. Flexbox makes it easy to create complex layouts and handle alignment, spacing, and distribution of items with minimal code. This tutorial will explain how Flexbox works, how to use it, and provide practical examples.

Table of Contents

  1. What is Flexbox?

  2. How Flexbox Works

  3. Flexbox Terminology

  4. Creating a Basic Flexbox Layout

  5. Flex Container Properties

    • Display

    • Flex Direction

    • Flex Wrap

    • Justify Content

    • Align Items

    • Align Content

  6. Flex Item Properties

    • Order

    • Flex Grow

    • Flex Shrink

    • Flex Basis

    • Align Self

  7. Practical Examples

    • Example 1: Simple Horizontal Navigation Bar

    • Example 2: Centering Content

    • Example 3: Responsive Card Layout

  8. Best Practices for Using Flexbox

  9. Cross-Browser Compatibility

  10. Conclusion


1. What is Flexbox?

Flexbox is a layout model introduced in CSS3 that provides a way to arrange and align items within a container, regardless of their size. It simplifies the process of creating complex layouts, making it easy to design responsive and flexible layouts that adapt to different screen sizes and content.

Key Concept:

  • Flexbox: A layout model that enables the creation of responsive and flexible layouts by distributing space and aligning items within a container.

Example:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

Explanation:

  • This example creates a flex container that centers its items both horizontally and vertically.


2. How Flexbox Works

Flexbox operates on a container (called a flex container) and its children (called flex items). The container defines how the items are arranged and aligned, while the items themselves can be sized and ordered flexibly.

Basic Process:

  1. Define the Flex Container: Set the display property of the container to flex.

  2. Arrange Flex Items: Use flex properties to control how the items within the container are aligned, ordered, and spaced.

  3. Adjust Flex Items: Apply properties to individual flex items to control their size, growth, and alignment.

Example Process:

  • A flex container is defined with display: flex.

  • The items are evenly spaced and centered within the container.


3. Flexbox Terminology

Before diving into Flexbox properties, it's important to understand some key terminology:

  • Flex Container: The parent element that holds the flex items. It is defined by setting display: flex.

  • Flex Items: The direct children of a flex container. These items are laid out according to the rules of Flexbox.

  • Main Axis: The primary axis along which flex items are laid out. It can be horizontal (row) or vertical (column).

  • Cross Axis: The axis perpendicular to the main axis.

  • Main Size: The width or height of a flex item along the main axis.

  • Cross Size: The width or height of a flex item along the cross axis.


4. Creating a Basic Flexbox Layout

Creating a basic Flexbox layout involves setting the display property of a container to flex, which makes all its direct children flex items.

Basic Syntax:

.container {
  display: flex;
}

Example:

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

Explanation:

  • The .container is now a flex container, and its items are spaced evenly with space between them.


5. Flex Container Properties

Flexbox provides several properties to control the layout of flex items within a container.

a. Display

The display property defines a flex container. Setting it to flex enables Flexbox.

Example:

.container {
  display: flex;
}

Explanation:

  • This turns the container into a flex container, making its children flex items.

b. Flex Direction

The flex-direction property specifies the direction in which the flex items are placed in the flex container.

Values:

  • row: Items are placed in a row (default).

  • row-reverse: Items are placed in a row but in reverse order.

  • column: Items are placed in a column.

  • column-reverse: Items are placed in a column but in reverse order.

Example:

.container {
  flex-direction: column;
}

Explanation:

  • The flex items are arranged in a column.

c. Flex Wrap

The flex-wrap property controls whether flex items should wrap onto multiple lines when they overflow the container.

Values:

  • nowrap: All items are placed on one line (default).

  • wrap: Items wrap onto multiple lines.

  • wrap-reverse: Items wrap onto multiple lines in reverse order.

Example:

.container {
  flex-wrap: wrap;
}

Explanation:

  • The flex items wrap onto multiple lines if necessary.

d. Justify Content

The justify-content property aligns the flex items along the main axis (horizontally if flex-direction is row).

Values:

  • flex-start: Items are aligned at the start of the container.

  • flex-end: Items are aligned at the end of the container.

  • center: Items are centered along the main axis.

  • space-between: Items are evenly spaced with the first item at the start and the last item at the end.

  • space-around: Items are evenly spaced with equal space around them.

  • space-evenly: Items are evenly spaced with equal space between and around them.

Example:

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

Explanation:

  • The flex items are evenly spaced with space between them.

e. Align Items

The align-items property aligns the flex items along the cross axis (vertically if flex-direction is row).

Values:

  • stretch: Items are stretched to fill the container (default).

  • flex-start: Items are aligned at the start of the cross axis.

  • flex-end: Items are aligned at the end of the cross axis.

  • center: Items are centered along the cross axis.

  • baseline: Items are aligned along their baseline.

Example:

.container {
  align-items: center;
}

Explanation:

  • The flex items are centered vertically within the container.

f. Align Content

The align-content property aligns the flex lines within the flex container when there is extra space on the cross axis. It only applies if the flex container has multiple lines.

Values:

  • stretch: Lines are stretched to fill the container (default).

  • flex-start: Lines are packed at the start of the container.

  • flex-end: Lines are packed at the end of the container.

  • center: Lines are centered in the container.

  • space-between: Lines are evenly spaced with the first line at the start and the last line at the end.

  • space-around: Lines are evenly spaced with equal space around them.

Example:

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

Explanation:

  • The flex lines are evenly spaced within the container.


6. Flex Item Properties

Flexbox also provides properties that can be applied to individual flex items to control their behavior within the container.

a. Order

The order property controls the order in which flex items are displayed within the flex container. By default, items have an order value of 0.

Example:

.item {
  order: 2;
}

Explanation:

  • This item will appear after items with lower

order values.

b. Flex Grow

The flex-grow property specifies how much a flex item will grow relative to the rest of the flex items when space is distributed within the flex container.

Example:

.item {
  flex-grow: 2;
}

Explanation:

  • This item will grow twice as much as other items with flex-grow: 1.

c. Flex Shrink

The flex-shrink property specifies how much a flex item will shrink relative to the rest of the flex items when space is lacking in the flex container.

Example:

.item {
  flex-shrink: 0;
}

Explanation:

  • This item will not shrink when space is limited, while other items with higher flex-shrink values will.

d. Flex Basis

The flex-basis property defines the initial size of a flex item before any space is distributed according to flex-grow and flex-shrink.

Example:

.item {
  flex-basis: 200px;
}

Explanation:

  • The item starts with a size of 200px.

e. Align Self

The align-self property overrides the align-items property for individual flex items, allowing you to align a single item differently from the rest.

Example:

.item {
  align-self: flex-end;
}

Explanation:

  • This item is aligned at the end of the cross axis, regardless of the container's align-items property.


7. Practical Examples

Let's explore some practical examples of using Flexbox.

Example 1: Simple Horizontal Navigation Bar

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Horizontal Navigation Bar - codeswithpankaj</title>
  <style>
    .navbar {
      display: flex;
      justify-content: space-around;
      background-color: #333;
      padding: 10px;
    }

    .navbar a {
      color: white;
      text-decoration: none;
      padding: 10px 20px;
    }
  </style>
</head>
<body>

<div class="navbar">
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Contact</a>
</div>

</body>
</html>

Explanation:

  • The navigation bar items are evenly spaced and centered within the container.

Example 2: Centering Content

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Centering Content - codeswithpankaj</title>
  <style>
    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f0f0f0;
    }

    .box {
      width: 200px;
      height: 200px;
      background-color: lightblue;
    }
  </style>
</head>
<body>

<div class="container">
  <div class="box"></div>
</div>

</body>
</html>

Explanation:

  • The .box is centered both horizontally and vertically within the .container.

Example 3: Responsive Card Layout

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Responsive Card Layout - codeswithpankaj</title>
  <style>
    .container {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
    }

    .card {
      flex: 1 1 calc(33.333% - 20px);
      background-color: white;
      border: 1px solid #ddd;
      padding: 20px;
      box-sizing: border-box;
    }

    @media (max-width: 768px) {
      .card {
        flex: 1 1 calc(50% - 20px);
      }
    }

    @media (max-width: 480px) {
      .card {
        flex: 1 1 100%;
      }
    }
  </style>
</head>
<body>

<div class="container">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
  <div class="card">Card 4</div>
  <div class="card">Card 5</div>
  <div class="card">Card 6</div>
</div>

</body>
</html>

Explanation:

  • The cards are displayed in a responsive grid that adjusts based on screen size. On larger screens, three cards are shown per row. On medium screens, two cards per row, and on smaller screens, one card per row.


8. Best Practices for Using Flexbox

When using Flexbox, consider the following best practices:

  • Use Flexbox for Layouts: Flexbox is ideal for layouts where items need to be evenly spaced, centered, or aligned in specific ways.

  • Combine with Media Queries: Use Flexbox with media queries to create responsive designs that adapt to different screen sizes.

  • Avoid Overusing Flexbox: While Flexbox is powerful, it is not always necessary for simple layouts. Use it where its features provide a clear benefit.

  • Test Across Devices: Ensure your Flexbox layouts work well on different devices and screen sizes.


9. Cross-Browser Compatibility

Flexbox is supported in all modern browsers. However, older versions of browsers like Internet Explorer may require vendor prefixes or fallbacks.

Example with Vendor Prefixes:

.container {
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flexbox;
  display: -o-flex;
  display: flex;
}

Explanation:

  • Including vendor prefixes ensures compatibility across different browsers.


10. Conclusion

CSS3 Flexbox provides a powerful and flexible way to create responsive and dynamic layouts. By mastering Flexbox properties and techniques, you can design layouts that are easy to manage, responsive to different screen sizes, and visually appealing.

  • Flex Container: Define a container with display: flex to start using Flexbox.

  • Flex Direction and Wrapping: Control the flow and wrapping of items within the container.

  • Alignment: Use justify-content, align-items, and align-content to align items within the container.

  • Flex Item Properties: Customize individual items with order, flex-grow, flex-shrink, and more.

By understanding and applying these concepts, you can create flexible and robust web designs that adapt to various layouts and devices.


For more tutorials and insights, visit Codes With Pankaj.

Last updated