Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why do we need a CSS flexbox?
3.
Working of CSS flexbox
4.
Flexbox Elements
4.1.
Container
4.1.1.
Display
4.1.2.
Flex-direction
4.1.3.
Flex-wrap 
4.1.4.
Flex-flow
4.1.5.
Justify-content 
4.1.6.
Align-items 
4.1.7.
Align-content 
4.1.8.
Perfect centering 
4.2.
Items
4.2.1.
Order
4.2.2.
Flex-grow 
4.2.3.
Flex-shrink 
4.2.4.
Flex-basis 
4.2.5.
The Flex property 
4.2.6.
Align-self
5.
Image Gallery Using Flexbox
6.
Responsiveness using CSS flexbox
7.
Frequently Asked Questions
7.1.
What is CSS flexbox used for?
7.2.
Is CSS flexbox responsive?
7.3.
How do you use the flexbox property?
7.4.
Is Flexbox better than CSS grid?
7.5.
Can one use CSS Grid and Flexbox together?
7.6.
What is a CSS grid?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

CSS Flexbox

gp-icon
Basics of javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction

CSS is an acronym for cascading style sheets. It is a markup-based web page and user interface style sheet language.

CSS Flexbox

CSS flexbox is a game-changing layout feature that makes it simple to create flexible and adaptive designs. Say goodbye to cumbersome CSS hacks and media queries, and hello to Flexbox, which allows you to align and distribute things in any direction, adjust their size and spacing, and adapt your layouts to every device. It's the modern web developer and UX designer's secret weapon, and it's here to make your life easier.

Why do we need a CSS flexbox?

  • Navigation: In navigation, we mostly need items to be displayed horizontally. This was hard to achieve before flexbox. 
     
  • Split navigation: If we want to align some navigation boxes to the right and some to the left then we need to use flexbox. It makes it much easier.
     
  • Center item: Before flexbox, it was harder to center an item. Now, with the use of flexbox, it’s a piece of cake.
     
  • Pushing footer down in card layout: If you use a card in a CSS grid, you can only control the alignments of the card in the grid and not the items inside the card like the card content or its footer. But by using flexbox, you can control all the parts. 
     
  • Media objects: You can make your page responsive very conveniently using flexbox for all the different devices. 
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Working of CSS flexbox

CSS allows laying out, aligning, and distributing space among items in “containers”. We can change the width and height of the objects to best fit the given area. We can expand and shrink items accordingly. Flexbox layouts are direction-agnostic as opposed to the other formats. 

Flexbox has two main types of elements, namely “container” and “items”.

Main Axis and Cross-axis

To understand flexbox, we have first to understand the concept of the main axis and cross-axis. 

  • The "flex-direction" feature determines the main axis. If the flex-direction attribute is row, the main axis is along the row; otherwise, the major axis is along the column. 
    On the main axis, flex elements move as a group.
     
  • The cross-axis is perpendicular to the main axis. The main axis is along the row if the flex-direction is row, and the cross axis is along the column if the flex-direction is column. You may move the objects individually or in groups so that they line up with one another and the flex container.

Flexbox axes

Flexbox Elements

As discussed above, there are two types of elements: container - the parent element, and items -  the child element.

Container

The Flexbox container includes several attributes for controlling the arrangement and placement of Flex items, including flex-direction, justify-content, align-items, align-content, and flex-wrap. These characteristics enables us to organize Flex objects vertically or horizontally, center them along the main or cross-axis, and regulate their spacing and wrapping.

Shown below is a flex container with three items

Flexbox Container

The properties of the flex container are:

Display

“display: flex” is used to make the flex container flexible.

Example

HTML

<div class="flex-container">
<div>1</div>
     <div>2</div>
     <div>3</div>  
</div>


CSS

.flex-container {
  display: flex;
  background-color: black;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
}


Result

Display flex container

Explanation

The above code generates a flex container that has three child divs. It has a black background and enables flexbox layout by using the display: flex attribute. The background colour of the child divs is #ff00ae, the text colour is black, the font weight is bold, and the font size is 30px, with a 10px margin and a 20px padding.

Flex-direction

‘Flex-direction’ determines the direction in which the container wants to stack the flex items. 

It has four different values: 

  • column (arrange the items vertically (from top to bottom)), 
  • row (place the items vertically (from left to right)), 
  • column-reverse (place the items vertically (from bottom to top)), and 
  • row-reverse(arrange the items vertically (from right to left)).
     

Example

HTML

<div class="flex-container">
<div>1</div>
     <div>2</div>
     <div>3</div>  
</div>


CSS

.flex-container {
  background-color: black;
  display: flex;
  flex-direction: column;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
}


Result

Flex direction CSS Flexbox

Explanation 

The above code creates a black flex container with three child divs using flexbox layout in a column direction. The child divs have a pink background, black text, and bold font at a size of 30px with 10px margin and 20px padding as mentioned in the code.

Flex-wrap 

Flex-wrap determines whether the flex items should wrap or not. 

It has three different values:  

  • wrap (specifies that the flex items will wrap if needed), 
  • nowrap(indicates that flex items shall not be wrapped), and 
  • wrap-reverse(specifies that the flex items will wrap if required, in reverse order).
     

Example

HTML

<div class="flex-container">
    <div>1</div>
    <div>2</div>
    <div>3</div>  
    <div>4</div>
    <div>5</div>
    <div>6</div>  
    <div>7</div>
    <div>8</div>
    <div>9</div>  
</div>


CSS

.flex-container {
  background-color: black;
  display: flex;
  flex-wrap: wrap;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Flex wrap CSS Flexbox

Explanation
This code creates a black flex container with nine child divs using flexbox layout, which wraps the elements to the next line when the container's width is exceeded. 

Flex-flow

The flex-flow is a shorthand property for setting both the flex-direction and flex-wrap properties. It has the value written of flex-direction and flex-wrap separated by a space.

Example

HTML

<body>
        <div class="flex-container">
            <div>1</div>
            <div>2</div>
            <div>3</div>  
            <div>4</div>
            <div>5</div>
            <div>6</div>  
            <div>7</div>
            <div>8</div>
            <div>9</div>
            <div>10</div>
            <div>11</div>
            <div>12</div>  
        </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  flex-flow: row wrap;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Flex flow CSS Flexbox

Explanation

The above code creates a black flex container with twelve child divs using flexbox layout that wraps the elements to the next line when the container's width is exceeded.

Justify-content 

To align the flex components, the justify-content attribute is utilised. It has five different values:  

  • center (aligns the flex items at the center of the container), 
  • flex-start(aligns the flex items at the beginning of the container), 
  • flex-end(aligns the flex items at the end of the container), 
  • space-around(displays the flex items with a space before, between and after them), 
  • space-between(shows the flex items with a space between them). 
     

Example

HTML

<body>
    <div class="flex-container">
        <div>1</div>
        <div>2</div>
        <div>3</div>  
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  justify-content: center;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Justify content CSS Flexbox

Explanation

This code creates a black flex container with three child divs using flexbox layout that centers the child divs along the main axis.

Align-items 

To align the flex elements, utilise the align-items attribute. It has five different values:  

  • center (aligns the flex items at the middle of the container), 
  • flex-start(aligns the flex items at the top of the container), 
  • flex-end(aligns the flex items at the bottom of the container), 
  • stretch(stretches the flex items to fill the container), 
  • baseline(aligns the items such as their baseline aligns). 
     

Example

HTML

<body>
    <div class="flex-container">
        <div>1</div>
        <div>2</div>
        <div>3</div>  
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  height: 200px;
  align-items: stretch;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Align items CSS Flexbox

Explanation

The above code creates a black flex container with three child divs using flexbox layout.The flex container has a fixed height of 200px and stretches the child divs vertically to fill the height. Each child div has a fixed width of 100px.

Align-content 

The align-content property is used to align the flex lines. 

It has six different values:  

  • space-between (displays the flex lines with equal space between them), 
  • space-around(displays the flex lines with space before, between, and after them), 
  • stretch(stretches the flex lines to take up the remaining space ), 
  • center(displays the flex lines in the middle of the container), 
  • flex-start(shows the flex lines at the start of the container), and 
  • flex-end(indicates the flex lines, which appear at the end of the container). 
     

Example

HTML

<body>
    <div class="flex-container">
        <div>1</div>
        <div>2</div>
        <div>3</div>  
        <div>4</div>
        <div>5</div>
        <div>6</div>
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  height: 400px;
  flex-wrap: wrap;
  align-content: space-between;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Align content CSS Flexbox

Explanation

This code creates a flex container with six child divs.The align-content property is set to space-between, which evenly distributes the space between rows in the container.

Perfect centering 

We can perfectly center an item by setting the ‘justify-content’ to center and ‘align-items’ property to center. 

Example

HTML

<body>
    <div class="flex-container">
        <div></div>
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
}


Result

Perfect Centering CSS Flexbox

Explanation

This code creates a black colored flex container in the body with a single div element inside, centered both horizontally and vertically, and colored in #ff00ae with bold font style and padding of 20px.

Items

Direct child elements of a flex container are called items. 

The properties of the flex item are 

  • Order
  • Flex-grow
  • Flex shrink
  • Flex basis
  • Flex property
  • Align self
     

Let's go through them one by one below. 

Order

This property specifies the order of the flex items. Using this, we can make the first flex item in the code appear as the last item in the layout.

Example

HTML

<body>
    <div class="flex-container">
        <div style="order: 3">1</div>
        <div style="order: 2">2</div>
        <div style="order: 4">3</div>
        <div style="order: 1">4</div>
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  align-items: stretch;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Order CSS Flexbox

Explanation

This code creates a flex container with four child divs that are styled with the order property to determine their position in the container. The child divs have a background color, font size, and width of 100px.

Flex-grow 

This attribute indicates how much a flex item will grow in comparison to the other flex items. The value must be a number, the default value is 0.

Example

HTML

<body>
    <div class="flex-container">
        <div style="flex-grow: 1">1</div>
        <div style="flex-grow: 1">2</div>
        <div style="flex-grow: 8">3</div>
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  align-items: stretch;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Flex grow CSS Flexbox

Explanation

The code creates a flex container with three div elements inside, where the third div has a higher flex-grow value, causing it to occupy more space within the container

Flex-shrink 

This property specifies how much a flex item will shrink relative to the rest of the flex items. The value must be a number, the default value is 1.

Example

HTML

<body>
    <div class="flex-container">
        <div>1</div>
        <div>2</div>
        <div style="flex-shrink: 0">3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
        <div>7</div>
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  align-items: stretch;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Flex shrink CSS Flexbox

Explanation

The above code creates a flex container with seven div elements inside. The third div element has a style of "flex-shrink: 0", which means it won't shrink when the container size is reduced.

Flex-basis 

This property specifies the initial length of the flex item. The value must be a number in pixels.

Example

HTML

<body>
    <div class="flex-container">
        <div>1</div>
        <div>2</div>
        <div style="flex-basis:200px">3</div>
        <div>4</div>
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  align-items: stretch;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Flex basis CSS Flexbox

Explanation

The above code creates a flex container with four child div elements. The third child div has a flex-basis of 200px, while the other divs have a width of 100px. The flex container aligns its items along the vertical axis, and other colour or font properties.

The Flex property 

This property is a shorthand for the flex-grow, flex-shrink, and flex-basis properties. The values of these are written and separated by spaces.

Example

HTML

<body>
    <div class="flex-container">
        <div>1</div>
        <div>2</div>
        <div style="flex: 0 0 200px">3</div>
        <div>4</div>
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  align-items: stretch;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
}


Result

Flex property CSS Flexbox

Explanation

The code creates a flex container with four child elements. The third child element has a fixed width of 200px and does not grow or shrink. The other child elements will stretch to fill the remaining space.

Align-self

This property specifies the alignment for the selected item inside the flexible container. It overrides the default alignment set by the container's align-items property. It has different values the same as the align-items property.

Example

HTML

<body>
    <div class="flex-container">
        <div>1</div>
        <div style="align-self: flex-start">2</div>
        <div style="align-self: flex-end">3</div>
        <div>4</div>
    </div>                                                
</body>


CSS

.flex-container {
  background-color: black;
  display: flex;
  height: 200px;
}

.flex-container > div {
  background-color: #ff00ae;
  color: black;
  font-weight: bolder;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
  width: 100px;
}


Result

Align self CSS Flexbox

Explanation

The above code creates a flex container with four child elements. The second and third child elements have the "align-self" property set to "flex-start" and "flex-end" respectively, which aligns them to the top and bottom of the container.

Image Gallery Using Flexbox

It may be difficult to create a basic image gallery. But kudos to Flexbox for making it so simple and easy to handle.

HTML

<div class="container">
           <img class="item" src="https://source.unsplash.com/random/320x241" alt="Image Gallery Using Flexbox">
           <img class="item" src="https://source.unsplash.com/random/321x240" alt="Image Gallery Using Flexbox">
           <img class="item" src="https://source.unsplash.com/random/321x241" alt="Image Gallery Using Flexbox">
           <img class="item" src="https://source.unsplash.com/random/319x240" alt="Image Gallery Using Flexbox">
           <img class="item" src="https://source.unsplash.com/random/320x239" alt="Image Gallery Using Flexbox">  
</div>


CSS

.container {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
  justify-content: space-around;
}
.item {
  margin: 5px;
}


Result

Image Gallery Using Flexbox

Explanation

The above code creates an image gallery extracting the images from the specified sources. It defines a flex container with wrapped items and a padding of 5 pixels, which are arranged with equal spacing around the container. The .item class specifies the margin for the items within the container.

Responsiveness using CSS flexbox

One can make responsive layouts that adjust themselves according to the screen size using Flexbox. For example, if we want to create a two-column layout for most screen sizes and a one-column layout for small screen sizes (which have width <=800px), you can change the flex-direction from row to column at a specific breakpoint of 800px. 

The same output of above code will look like this in Galaxy Fold(phone): 

Responsiveness using CSS flexbox

In the dimension of 1017X488 the output will look alike:

Responsiveness using CSS flexbox

Frequently Asked Questions

What is CSS flexbox used for?

CSS flexbox is used to easily format HTML and to align and display items properly.

Is CSS flexbox responsive?

Yes, CSS flexbox is responsive.

How do you use the flexbox property?

We use flexbox properties by assigning different values to them, which places the objects in a given space correctly.

Is Flexbox better than CSS grid?

Flexbox mostly helps align content & move blocks. CSS grids are for 2D layouts. Flexbox works best in a single dimension (either rows OR columns), while CSS grid is better to use in two dimensions. Therefore, both have their advantages.

Can one use CSS Grid and Flexbox together?

Of course, the CSS grid and Flexbox can work together in a layout. You can use Flexbox inside the CSS grid and vice versa.

What is a CSS grid?

The CSS Grid Layout Module provides a grid-based layout system with rows and columns, making web page creation easier without the usage of floats and positioning.

Conclusion

In this article, we’ve learned about CSS flexbox and its properties. Using Flexbox in one of the practical projects would make things crystal clear about this topic. It's always suggested to try and use whatever you learn in CSS practically. You can also refer to the following blogs related to CSS

  1. Introduction to CSS
  2. CSS Position
  3. CSS Selectors
  4. CSS Interview Questions
  5.  Versions of CSS
     

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

If you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning, Ninjas!

Previous article
CSS First Child
Next article
nth child Selector in CSS
Guided path
Free
gridgp-icon
Basics of javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass