Common Use Cases of CSS Flexbox
Tags: css, html, webdev, flexbox
Published: 2021-06-02 12:43:03

The last two posts of this series on ***CSS Flexbox*** focused on all the properties of flexbox applied to flex-container and flex-items.

> _*In this post, we will go through some of the popular and common use cases of CSS flexbox.*_

> This post is quite long as I have explained all the use cases in detail.

***At the end of this blog post, I will also share some useful resources to learn CSS Flexbox in the easiest possible way!***


<hr/>

# COMMON USE CASES OF CSS FLEXBOX
1. [Aligning items with space between](#1-aligning-items-with-space-between)
2. [Aligning items horizontally](#2-aligning-items-horizontally)
3. [Centering content](#3-centering-content)
4. [Splitting a container halfway](#4-splitting-a-container-halfway)

_We will use the example in the images below and try to see how flexbox was used create this webpage._
   ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xc2hsgqo5jtlhkwn3tef.png)
   ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xmtqsnzjpuhl21u3qc5y.png)
   ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zimr00lk705n32w0o6e.png)
  
[Find the template code for the website here](https://codepen.io/bhaaratii/pen/qBrxRNe)
  
<br />


### 1. ALIGNING ITEMS WITH SPACE BETWEEN
***One use of flexbox is to align elements with space between them.***

* In the example website, navbar in the header has 2 sections: ***logo*** and the ***navigation links***. 
* They are placed such that there is _space between_ them, and are pushed to either side of the navbar.

* Using the template code below for the navbar, let's see how the logo and navbar can be pushed with space between them.   
      {% codepen https://codepen.io/bhaaratii/pen/YzZEVay default-tab=html,result %}

* To convert this into a proper navbar, we need to focus on the parent of both `<h1>` and `<nav>`: ***the div with `navbar` class***.
      ```css
      .navbar {
          display: flex;
          justify-content: space-between;
          align-items: center;
      }
      ```
* That's all! 3 lines of code and then logo and navigation links are pushed to either sides with space between. 

<br />

* `display: flex` converts the _navbar_ container into a flex-container. 
  * The `<h1>` and `<nav>` are placed horizontally. `flex-direction: row;` is the default main-axis.
  * `justify-content: space-between;` separates the flex-items with space between them and pushes them to opposite sides of the container (main-start and main-end).
  * `align-items: center;` places the flex-items in the vertical center of the flex-container.
      * ***NOTE***: When `justify-content: space-between;` is used on a container with more than 2 flex-items, then they are spread out within the container, with 1<sup>st</sup> item near the main-start and last item pushed to main-end. 
      * This can be used in the situation when header only has navlinks.
    * [Go through this post to learn about justify-content](https://dev.to/bharati21/css-flexbox-making-layout-design-easy-part-1-24l5)

Check out the GIF below to understand how the above code works. 
  ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ob9jxt803mc7li750tr.gif)

This is the final look of the navbar with space between the logo and navlinks.
  {% codepen https://codepen.io/bhaaratii/pen/MWpOoBg default-tab=html,result %}
  
   
### 2. ALIGNING ITEMS HORIZONTALLY
***Another common use case of flexbox is to align items horizontally within a container***

* In the example website, the navlinks have been placed horizontally within the navbar. 
* [In the example use case 1 above](#1-aligning-items-with-space-between), logo and the navlinks have been placed properly, but the navlinks are still displayed _vertically_.


* Using the code below as template, let's see how the navigation links can be aligned horizontally.
      {% codepen https://codepen.io/bhaaratii/pen/MWpOoBg default-tab=html,result %}


* To align all the navlinks horizontally, we need to focus on the `<ul>` and `<li>` within `.navbar nav`.
      ```css
      .navbar nav ul {
          display: flex;
      }
      ```

<br />
  * `display: flex` makes sure the `<ul>` becomes a flex-container, and by default all the children, `<li>` are horizontally aligned.


Check out the GIF below to understand how this works. 
  ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nxd3nhs3o4jir2u8d98s.gif)

This is the final look of the navlinks within the navbar.
  {% codepen https://codepen.io/bhaaratii/pen/eYveRjN %}
    
     

### 3. CENTERING CONTENT
***This is probably the most common use case of flexbox: to center content vertically and horizontally.***

* In the example webpage above, notice how text within the showcase image is centered vertically as well as horizontally.

* Using the below starter code, let's see how text (or any other content!) can be centered within a container.
      {% codepen https://codepen.io/bhaaratii/pen/gOmXXGv default-tab=html,result %}

* We need to grab the parent container of the content that needs to be centered.
* In this case, parent element of `<h1>`, `<p>` and `<a>` is the ***div with id `showcase-content`***.
      ```css
      #showcase-container {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
      }
      ```
<br />

* Here the main-axis is column, so applying flex to the `#showcase-container` stacks `<h1>`, `<p>` and `<a>` vertically.
  * `justify-content: center;` centers content along the main-axis: column. 
  * `align-items: center;` aligns content to the center along the cross-axis: row.
      * Using these together centers content vertically and horizontally.
  * ***NOTE***: You can play around with combinations of `justify-content` and `align-items` to test various alignment of elements within the parent container. 
    * [Check out this post to learn more about justify-content and align-items](https://dev.to/bharati21/css-flexbox-making-layout-design-easy-part-1-24l5)

Check out the GIF below to understand how centering content works. 
  ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dcia4o5f578ano7z4t6l.gif )

This is the final look of the showcase and text within.
  {% codepen https://codepen.io/bhaaratii/pen/LYWOQxv %} 


### 4. SPLITTING A CONTAINER HALFWAY
***The main agenda behind flexbox is that it easily aligns elements even if the initial size is unknown or dynamic.***

* In the example webpage above, the cards in the main section are split such that one half has an image and the other half content.


* Using the below starter code, let's see how we can into two equal sections.
      {% codepen https://codepen.io/bhaaratii/pen/YzZYPZv
 default-tab=html%}

* As usual let's grab the parent container of the container that needs to be split.
* The parent of `<img>` and `<h3>`, `<p>` container with class `card-body-column`, which is the ***div with class `card-body`***.
      ```css
      .card-body {
          display: flex;
          flex-wrap: wrap;
          justify-content: center;
      }
      ```
<br />
* The above code makes both the div with class `card-body-column` flex-items.
  * Although these 2 items are supposed to be aligned horizontally they are wrapped onto different lines since their initial width overflows the container. This behavior is due to `flex-wrap: wrap;`

<br />
* Let's now focus on aligning the items horizontally for which we need to grab the container with class `card-body-column`.
      ```css
      .card-body .card-body-column {
          flex: 1;
      }
      .card-body img {
          height: 100%;
          width: 100%;
          object-fit: cover;
      }
      ```
<br />
* Adding `flex: 1;` to `.card-body-column` makes the container grow or shrink from same initial `width: 0`. Hence, now we obtain 2 equal containers that grows equally.
  * But the image does not occupy the entire part of the container, hence we set the width and height to 100%. 
  * To ensure that width to height ratio is not distorted as the container shrinks or grows we also add `object-fit: cover;`. This places the image as a cover in it's part of the container. 
  * ***NOTE***: We can split the containers into sections of different ratios by increasing the value of `flex` for one half of the container.

Check out the GIF below to understand how splitting of content works. 
  ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vypa2eujdlkp2e3s2l9u.gif)

Check out the GIF below how `object-fit: cover;` helps the image.
  ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xmidf7z69k4szc69vbrt.gif)

This is the final look of the showcase and text within. 
  {% codepen https://codepen.io/bhaaratii/pen/JjWMzJj %} 

<hr />

# FLEXBOX AND MEDIA QUERIES
* A good website is one that works seamlessly on all devices of all sizes.
* Although flexbox makes layouts easy, we need to add responsiveness. This can be done using media queries.
* Let's look at the image within the [card container mentioned above in use case 4](#4-splitting-a-container-halfway).
  ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgkjfjcvx891dyamvyyt.png)

* Notice how this image shrinks in screens of small sizes. This obviously isn't very appealing. So let's tackle this issue.
* Let's set a max width and ensure that once the screen width becomes smaller than the max-width, we will change the `flex-direction` to column.
* This way when the screen size becomes too small, the card content will be stacked on top of each other hence avoids shrinking.

<br/>
```css
@media (max-width:540px) {
    .card-body {
         flex-direction: column;
    }
}
```
<br />
* As the screen size becomes less than 541px, the main-axis becomes column. Otherwise, it's the default row.
  ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d53o1jenk7bipetd2d04.png)

The same responsiveness can be applied to the logo and navlinks to be stacked vertically and in the center the navbar.

<hr />

* Using just 4 common use cases, we managed to build a small webpage! [Find the completed website code here](https://codepen.io/bhaaratii/pen/dyvdNpP)


There are so many more use of flexbox out there which you can easily discover by tinkering with flexbox properties and creating websites.

* _As as a side note, different developers use varying combinations of flex properties to bring out the same effect._ 
  * For e.g. to separate the logo and navlinks, you may see that `justify-content: space-between` may not be used, but rather `align-self` is used on the individual flex-items.
<br />

* Another major takeaway is that flexbox is not the end of responsive design, and this may not be the easiest solution for certain situations.
  * For e.g., say you want to split your website into header, main, sidebar and footer. In such cases, ***CSS GRID*** is much more _simpler_ and _faster_.

> ***THERE IS NO SINGLE RIGHT WAY TO DO THINGS! YOU ADAPT AND LEARN AS YOU EXPLORE!***

<hr />

# RESOURCES
As promised, I'll drop a few resources that helped me in learning CSS Flexbox easily and efficiently. Hope this helps you.
* [CSS MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout): Take your time to read through the docs as the explanations are highly detailed and precise.
* [CSS Tricks](https://css-tricks.com/snippets/css/a-guide-to-flexbox/): Another gem of a resource where basics for flexbox are explained as well.
* [W3C Flexbox Docs](https://www.w3.org/TR/css-flexbox-1/): A very detailed and in-depth understanding to CSS Flexbox
* [W3Schools](https://www.w3schools.com/css/css3_flexbox.asp): Another resource having short explanations with good examples

These aren't enough as once you grasp the theory, you will have to apply them somewhere. 

> Below are some fascinating games and challenges which will help you understand flexbox practically AND visually!

* [Flexbox Defense](http://www.flexboxdefense.com/)
  * A wonderful fantasy game where you use flex properties to stop enemies from getting into your defenses.
* [Flexbox Froggy](http://flexboxfroggy.com/)
  * Another game where flex properties are used to help froggy and friends to guide them to their lillipads!
* [Flexbox Code Generator](https://the-echoplex.net/flexyboxes/)
  * This site allows you to visualize flex properties, and play around by changing combination of properties
* [Building UI with CSS Flex](https://www.flexboxpatterns.com/)
  * This site has challenges for you to build neat, and awesome UIs with the help of CSS Flexbox.
* [Dev Challenges](https://devchallenges.io/)
  * Another website that has front-end and responsive web developer challenges to build components and sites!

<hr />

And that's a (flex) wrap on the CSS Flexbox series.

Thank you so much for going through the blog post and sticking till the end. 
Please do leave a like and share it with your dev friends!