Mastering Flexbox in CSS: A Comprehensive Guide for Responsive Web Design

CSS

Learn how to master Flexbox in CSS with our comprehensive guide. Understand the key properties like flex-grow, flex-shrink, and flex-basis to create responsive, flexible web layouts. Perfect for web developers looking to enhance their design skills and improve website performance.


NGNishan Giri
2024-08-30
Mastering Flexbox in CSS: A Comprehensive Guide for Responsive Web Design

Flexbox is a powerful tool in CSS that helps you create layouts that adjust smoothly to different screen sizes. Whether you're building a simple navigation bar or a complex grid, Flexbox makes it easier to design responsive and flexible web pages. In this guide, we’ll explore the basics of Flexbox, break down its key properties, and show you how to use it to make your web designs more adaptive and user-friendly.

Getting Started with Flexbox

To help you get hands-on with Flexbox, let's start with a simple example. We'll use basic HTML and CSS to create a layout with multiple boxes inside a container. This will allow you to see Flexbox in action and understand how it can be used to arrange elements on your web page.

HTML Structure

Here’s the basic HTML structure for our example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mastering Flexbox in CSS</title>
    <link rel="stylesheet" href="./style.css">
  </head>
  <body>
    <div class="main">
      <div class="box">1</div>
      <div class="box b2">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
    </div>
  </body>
</html>

This structure includes a container <div> with a class of main, and five child <div> elements inside it, each with a class of box. These boxes are where we'll apply Flexbox styling.

Basic CSS Styling

Let's start with some basic CSS to style the boxes and the container:

* {
  margin: 0;
}
 
.main {
  background-color: #1b212c;
}
 
.box {
  background-color: #447bbe;
  color: #f8f8ff;
  font-size: 30px;
  padding: 35px;
  margin: 10px;
  width: 20px;
}

Result:

Flex box: step-1

display: flex

To turn this basic layout into a Flexbox-powered layout, we’ll need to update the .main class with flex-box properties:

.main {
  background-color: #1b212c;
  display: flex;
}

Result:

Flex box: step-2.0

flex-direction: row

You might have noticied that just by applying display: flex. The layout has changed to row layout. This is because of its default behaviour which is same as adding flex-direction: row property. Lets add flex-direction property and see how the layout changes.

.main {
  background-color: #1b212c;
  display: flex;
  flex-direction: row;
}

Result:

Flex box: step-2.1

After adding the flex-direction: row property changes nothing as we are setting it to row which is the default behaviour.

justify-content

Now let's check what justify-content propery actually does.

.main {
  background-color: #1b212c;
  display: flex;
  flex-direction: row;
  justify-content: center;
}

Result

Flex box: step-3

The justify-content: center centers the flex items horizontally within the .main container. It has several values, each controlling the horizontal alignment of flex items within the container:

flex-start: Aligns items to the start (left) of the container.

flex-end: Aligns items to the end (right) of the container.

center: Centers items horizontally in the container.

space-between: Distributes items evenly with the first item at the start and the last item at the end.

space-around: Distributes items evenly with equal space around each item.

space-evenly: Distributes items so that the space between them is equal, including at the edges of the container.

These options give you flexibility in how you arrange items horizontally within a Flexbox container. Play around these values to see how the layout in the container changes.

flex-direction: column

Now, lets change flex-direction property and see how the layout changes.

.main {
  background-color: #1b212c;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

Result:

Flex box: step-4

flex-direction: column property has now changed the layout to column format. Don't get confused now thinking why the boxes have gone to the starting of the container. This is where come the property align-items.

align-items

This property vertically centers the flex items within the container along the cross axis (which is usually the vertical axis when flex-direction is set to row). Lets update our CSS and see how it changes the layout.

.main {
  background-color: #1b212c;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

Result:

Flex box: step-5

The boxes are now align vertically center along the cross-axis.

Note: "The main axis determines the direction in which the items are arranged, and the cross axis is the perpendicular direction. Understanding these axes is key to effectively using Flexbox to control layout."

The align-items property in Flexbox has several values that control the alignment of flex items along the cross axis (which is usually the vertical axis when flex-direction is set to row). Here’s a list of all the possible values:

flex-start: Aligns items to the start of the cross axis (top if flex-direction is row).

flex-end: Aligns items to the end of the cross axis (bottom if flex-direction is row).

center: Centers items along the cross axis.

baseline: Aligns items such that their baselines align. This is particularly useful when you want text inside flex items to line up.

stretch: Stretches items to fill the container along the cross axis. This is the default value. If the items don't have a specific height set, they will stretch to fill the container.

Each of these properties gives you control over how flex items are aligned within their container, allowing for a wide range of layout possibilities in responsive design.

flex-wrap

The flex-wrap property in Flexbox controls whether flex items are forced into a single line or allowed to wrap onto multiple lines. Now let's see the usage of flex-wrap property. Try giving 2 box some width and see what happes. You can modify the see file like below & see.

* {
  margin: 0;
}
.main {
  background-color: #1b212c;
  display: flex;
}
 
.box {
  background-color: #447bbe;
  color: #f8f8ff;
  font-size: 30px;
  padding: 35px;
  margin: 10px;
  width: 20px;
}
 
.b2 {
  width: 300px;
}

Result

Flex box: step-6

You can see that when the screen size is smaller the remaining boxes are overflow from the screen this is due to the default behaviou which sets the flex-wrap property to nowrap;

Now, let give the container a flex-wrap: wrap property.

Flex box: step-6.1

So now the boxes are not overflowing from the screen rather they are moved to the new line.

Note: "You can also use a shorhand called flex-flow for setting both `flex-direction` and `flex-wrap`. Example: flex-flow: column wrap;"

order

Controls the order in which flex items appear in the flex container. The default is 0, but this can be set to any integer value, positive or negative usually -1 or 1. Lets see it in action. Apply below CSS to the b2 box.

.b2 {
  order: 1;
}
order property

The box 2 is now coming after all the items inside the container as we gave the value as 1. Try giving it -1 and see what happens!!

flex-grow

Defines the ability of a flex item to grow if necessary. A value of 1 means the item will grow to fill the container, relative to the other flex items. Add below property for b2 box and see what happens now.

.b2 {
  width: 300px;
  flex-grow: 1;
}
flex-grow

Notice how box b2 is now taking all the remaining spaces.

flex-shrink

Defines the ability of a flex item to shrink if necessary. A value of 1 means the item can shrink, relative to the other flex items. Lets modify the css for box b2 and see.

.b2 {
  width: 300px;
  flex-shrink: 1;
}
flex-shrink

Notice how the box b2 is taking only the required space unlike flex-grow. Try minimizing the screen and see how it behaves.

Note: "flex-grow controls how much a flex item can grow relative to the other flex items in the container when there is extra space available where flex-shrink controls how much a flex item can shrink relative to the other flex items in the container when there is not enough space available."

flex-basis

Defines the default size of an element before the remaining space is distributed. It can be set to a specific size (e.g., 200px) or auto. Apply the below css to b2 box and see.

.b2 {
  flex-basis: 200px;
}

flex-basis: 200px;: This sets the initial size of the .b2 flex item to 200px before any space distribution occurs based on flex-grow or flex-shrink. This means that .b2 will attempt to take up 200px of space in the flex container. If the container has more or less space, other properties like flex-grow and flex-shrink will determine how the space is adjusted.

flex-basis
Note: "You can use a shorthand for setting `flex-grow`, `flex-shrink`, and `flex-basis` together with just `flex` property. Example: flex: 2 1 150px;"

Test your learning in the below website.

https://flexboxfroggy.com/

Conclusion

Mastering Flexbox is essential for creating responsive, flexible, and modern web layouts. By understanding properties like flex-grow, flex-shrink, flex-basis, and the shorthand flex, you can control the behavior of your elements within a container, ensuring they adapt seamlessly across different screen sizes. Whether you’re building complex grids or simple navigation bars, Flexbox provides the tools to make your designs robust and user-friendly.

For more insights and practical examples on Flexbox and other CSS techniques, stay tuned to our blog and continue refining your web development skills.