Create Your Own CSS Flexbox Grid - Day 16

There are a ton of great CSS Frameworks out there and a few of my favorites are Bootstrap, Foundation, Bulma. One of the main features of these frameworks is the grid system which are great when you are first starting out. The problem I have with these though (especially with Bootstrap) is that they can be very bloated and difficult to understand how everything is working together.

So that’s why we are going to go ahead and create our own CSS Framework, starting with the core piece…the Grid system using Flexbox! The key to the grid system it placing items where you intend them to be on all screen sizes from a desktop, laptop, tablet & phone all with the most streamlined code possible.

How Do We Accomplish This?

Now there are two different methods we are going to introduce, you will most likely end up using both depending on how you want weren’t elements to react to various screen sizes.

Method #1 Pure Flexbox

In this method you are allowing Flexbox to take care of the mobile breakpoints and will obviously vary depending on the content. If you want to force a certain width to a div then specify the width and then Flexbox will handle moving items around that until there is enough space available. It is a super clean and streamlined method but those pixel-perfect graphic designers out there may not approve as it lacks some of the flexibility working with percentages in method #2.

.flex  {
  display: flex;  /* Required Class for Flexbox to Work */       
  flex-wrap: wrap; /*  Allows items to move to the next line if screen size gets too small for elements*/ 
}

.center {
  justify-content: space-around; /* Center item horizontally */
  align-items: center; /* Center item vertically */
}

Method #2 Classic Grid System + Flexbox

* Method should still use .flex class from above on parent item to align items, grid system will handle div width and mobile view *

This is a typical grid system in which section are divided into 12 equal parts. If you want two items to take up half the screen you give each div a class of .flex-6 and if you then what those same elements to expand full screen on mobile add .flex-mobile-12 as this will override the .flex-6 with the media query below at 480 pixels.

.flex-12 {
  width: 100%;
}
.flex-6 {
  width: 50%;
}
.flex-4 {
  width: 33.3333%;
}
.flex-3 {
  width: 25%;
}

@media only screen and (max-width : 480px) {
.flex-mobile-12 {
  width: 100%;
}
.flex-mobile-6 {
  width: 50%;
}
.flex-mobile-4 {
  width: 33.3333%;
}
.flex-mobile-3 {
  width: 25%;
}
}

Conclusion

Check out the video below for a more in-depth overview for the Zero to Startup in 30 Days Challenge.

Create Your Own CSS Flexbox Grid

Coming Tomorrow -----> Building Out Our Navigation

Want To Learn How To Turn Your Ideas Into Code?


Written by Tim Moreton who lives and works
in Philadelphia building useful things.