5 Minute Guide to Learning Flexbox (Why You Should Stop Using Floats)

Flexbox Basics

Flexbox (or Flexible Box Layout Module) was designed to give web designers an easier way to build their html layouts. Here I will give you basic flexbox layout examples to learn from and build off. Learn the differences between flexbox vs grid.

This is not a complete guide to flexbox, but in this article I will teach you the properties you must know.

In addition, I wrote an article on the 12 Exciting New Magic CSS3 Selectors You Need To Know In 2017 you may also find useful.

As you may already know, before flexbox, web designers relied heavily on floating divs with percentage widths to achieve their desired layout – as explained in this Tutsplus article.

Flexbox Container

First, in order to declare an element as flexbox, add “display: flex” to its properties.

#container {
display: flex;
}

align-items

Second, in the container, define how you want the children to align using the “align-items” selector.

#container {
align-items: flex-start | flex-end | center | stretch | baseline;
display: flex;
}

Here are visual representations of the different align-item values:

visual display of flexbox align-items flex-start value

visual display of flexbox align-items flex-end value

visual display of flexbox align-items center value
align-items: center will keep each child centered vertically throughout the row of columns.

visual display of flexbox align-items stretch value
align-items: stretch will stretch each child to the container’s height. Stretch is the initial value for align-items.

visual display of flexbox align-items baseline value
align-items: baseline sets the children to align themselves to keep the start of the content aligned together at the top.

Play around with these settings in this flexbox playground I setup for you. Also, be sure to change the container’s align-items value to one of the values shown above. To do this, click on the “Edit on Codepen” link in the upper-right hand corner of the preview box below.

See the Pen Flexbox Item Align Example by Thomas Hare (@tommyhare) on CodePen.0

See more details about align-items at the Mozilla Developer docs.
Also: Traditional uses of float, clear and vertical-align don’t have affect on flex items.

align-self

Now, when you need custom alignment on a specific child in a container, use align-self. Align-self will overwrite the container’s  align-item value on the specific child.

#container > #child-3 {
align-self: flex-start | flex-end | center | stretch | baseline;
}

See more information about align-self at the Mozilla Developer docs.

justify-content

Keep in mind, you may need to bookmark this page to refer back to these values. Provided that, it can be daunting to try and remember these values.

Luckily the distributed alignment values below are the most common used.

Distributed alignment values:

#container {
justify-content: space-between | space-around | space-evenly | stretch;
}
  • flexbox space-between items will give you an even spacing between elements in your container.
  • space-around will give you even spacing around elements in your container, including space around the container’s left and right sides.
  • space-evenly items are evenly distributed in the container, giving the exactly same space between elements.
  • stretch items stretch to keep equal height children inside the container.

Positional alignment values:

#container {
justify-content: center | start | end | flex-start | flex-end | left | right;
}

Baseline alignment values:

#container {
justify-content: baseline | first baseline | last baseline;
}

Read more about justify-content at the Mozilla Developer docs.

Benefits to Using Flexbox

A major benefit to using it is for easy alignment. Notably, it takes the guess work out of element positioning.

Look:

Take this type of flexbox layout example
display of the structure of sidebar and content

You can create this layout with the code below.

Here is the HTML:

<div id="container">

<div id="header"></div>

<div id="article">
<div class="content"></div>
<div class="footer"></div>
</div>

<div id="sidebar"></div>

<div id="footer"></div>

</div>

…and the CSS

body {
padding: 10px;
}

#container {
display: flex;
flex-wrap: wrap;
}
#container > div {
margin: 10px;
}

#header {
background-color: #3F4CFF;
height: 80px;
width: 100%;
}

#article {
width: 68%;
}
#article > .content {
height: 400px;
background-color: #3F4CFF;
}
#article > .footer {
background-color: #3F4CFF;
height: 60px;
margin-top: 10px;
}
#sidebar {
background-color: #3F4CFF;
flex: 1;
width: 35%;
}

#footer {
background-color: #3F4CFF;
height: 80px;
width: 100%;
}

The output of this should resemble this:

See the Pen Flexbox Item Align Example by Thomas Hare (@tommyhare) on CodePen.1

Because this is a newer web technology, it may or may not render correctly in your browser. See if your browser supports Flexbox.

As of December 2017, Mozilla Firefox and Google Chrome are the two major browsers to support the CSS Flexible Box Layout Module.

What’s the benefit?

Because I am using flexbox, the sidebar width and height do not need to be set.

Both height and width of the sidebar scale with the main content.

Before, by using the CSS float method, this wasn’t possible and it was a pain to get the sidebar to match the main content’s height.

For example:

Say you had a larger sidebar and a page with a small amount of content, the page would end up looking something like this:
display of the structure of sidebar and content

Flexbox VS Grid

To begin with, the CSS grid was first introduced as a W3C Working Draft on November 6, 2012. Now, nearly 10 years later it’s classified as Candidate Recommendation since 

Further, checking on caniuse CSS grid layout, it’s supported by mainly Mozilla Firefox and Google Chrome.

One of the main differences with CSS grid is the ability to map out both columns and rows. In the same fashion, create a grid display by adding “display: grid” to the container element’s CSS.

Like this:

#container {
display: grid;
}

Here’s an example of what CSS grid layouts have the ability to build. Notice, there are both rows and columns.
CSS grids will give you more control over your content layout.
Example of flexbox vs grid layout - demonstrating rows and columns

Basic CSS Grid Attributes

  • CSS grid template rows will define height of rows.
    Example: grid-template-rows: 100px auto 100px;
  • CSS grid template columns will define width of columns.
    Example: grid-template-columns: 200px 100px 200px;
  • grid row gap will give you spacing between rows.
    Example: grid-row-gap: 25px;
  • grid column gap will give spacing between your columns.
    Example: grid-column-gap: 10px;
  • grid gap will set both row and column gaps.
    Example: grid-gap: 15px;

Here:

This is a visual representation of what grid-column-row and grid-column-gap affect in a grid display.
CSS grid grid-column-gap and grid-row-gap reference graphic

If you would rather just declare one same CSS grid gap for both columns and rows, you would use the grid-gap attribute instead.

Grid Item Alignments

justify-items

This selector will give you the ability to align your content horizontally inside your container’s cells.
a visual representation of how the CS grid justify-items selector works

#container {
display: grid;
justify-items: start | end | center | stretch;
}

align-items

Much like justify-items, this selector will give you the ability to align your content. However, rather than aligning your content horizontally, you are now aligning vertically. Much the same, the terms for alignment work in the same manner, just vertically.
a visual representation of how the CSS grid align-items selector works

#container {
align-items: start | end | center | stretch;
}

Building Layouts With CSS Grid

A simple 3 column grid’s CSS would look something like this: This will create column widths of 25% – 50% – 25%.

#container {
display: grid;
grid-template-columns: 25% 50% 25%;
grid-gap: 10px;
}

#container > div {
background-color: #444;
color: #FFF;
}

This CSS grid code will give you a layout like this:
a visualization of the CSS grid template columns attribute

Summing Up:

Flexbox was created to make layout design easier for web designers. Along with, lots of CSS frameworks like Bootstrap V4 are beginning to adapt it.

With that being said, it’s a valuable skill for you to learn.

Use this article to develop a quick understanding of how it works and how to design layouts using flexbox. Equally important, you will learn the difference between it and the CSS grid layout – find out basic use cases for each in your projects.

Leave a comment on your thoughts about the direction of Flexbox. Do you believe other browsers will adopt flexbox or phase it out in favor of the more precise CSS grid?

Using Stylus to Build a Web Framework Like Bootstrap and Foundation

What is Stylus?

To begin with, Stylus is a CSS preprocessor like SASS or LESS with much of the same basic functionality. However, using Stylus offers a cleaner – easier to read and understand syntax.

To begin with, I believe the best way of learning, is through building. Which is why I will be walking you through the process of building a simple CSS grid framework using Stylus to generate it.


History of CSS Web Framework Design

In the past, we built CSS frameworks using lots of copy and pasting of much of the same code with slight variations. Without a doubt, this made updating and managing the frameworks repetitive and time consuming.

However, now with CSS preprocessors and the help of automation tools like NPM, Gulp and Grunt we can automate the process and rebuild them within seconds.

Blueprint (The First Web Framework)

To begin with, Blueprint was created by Olav Bjørkøy and released on August 3, 2007. Blueprint includes a 24 column “span” grid layout. Blueprint didn’t support mobile displays by default.

YAML and Cascade CSS Framework Soon Followed Behind

Comparatively, Cascade was one of the first CSS web frameworks to support responsive design. However, it required multiple different CSS files which increased page load time.


A sketch of a CSS web framework like Bootstrap.

Popularity of Bootstrap and Grid Frameworks

Grid frameworks allow designers to easily layout content on web pages. In addition, grids can be resized depending on different screen sizes with the use of media queries introduced in CSS3.

Media Queries and Grid Frameworks

As you may know, Bootstrap CSS framework offers classes ranging from “col-xs-X” to “col-xl-X”. (X representing the column size.) By way of example, these column names start with “xs” and “xl” to dictate extra-small and extra-large screen sizes.

But why use these class names?
By using these descriptive class names you can easily dictate the width of elements for all different device sizes.

How to Use Stylus to Build a Grid Based Web Framework Like Bootstrap or Foundation

Creating a Basic CSS Grid Framework Using Stylus

In order to create a CSS grid using Stylus, you must first understand how the Stylus for statement works. By way of example, here’s how you would build a basic grid using the Stylus the “for” statement. Granted, due to this being just a basic grid, there is no support for responsive column sizes just yet.

//Default grid settings
columns = 12
gutter = 15px

//Set all elements to border-box
*, *:before, *:after
box-sizing: border-box

.container
float: left
padding: 0 gutter
width: 100%

.row
float: left
margin-left: -+gutter
margin-right: -+gutter
width: 'calc(%s + %s)' % (100% gutter*2)

[class^='col-'], [class*=' col-']
border: solid rgba(0,0,0,0.15) 1px
float: left
padding-left: gutter
padding-right: gutter

for i in (1..columns) {
.col-{i} {
col-width = 100%/(12/i)
width: col-width
}
}

This type of CSS grid utilizes a row to negate the left padding of the first column and right padding of the last column. Coupled with, the [class*=col-] part of this is saying all class names that begin with “col-“ will be affected with the internal styles.

We’re ensuring the box-sizing is set to border-box to keep the border, margin and padding within the inside of the columns. Float is necessary to keep elements in a row to fill the 12 column space. I set padding on the left and right of columns to the gutter-size. It’s important to keep these values matching the negative margin set in the .row class.

As for the “for i in (1..columns)” part… this is saying for every iteration from 1 until the defined column count (12), create that new column size.

sparking blue electricity traveling through a maze

A Deeper Understanding of the Stylus For Loop

In the for statement near the bottom, we have a loop running from 1 to 12 as dictated by the “(1..12)” part. Equally important, there is a class using that iteration “i” for the column size “.col-{i}” – Which will be cycled through from 1 to 12 as “col-1” to “col-12” representing each column’s width.

Stylus allows for variables and logic, so we create a variable called “col-width” to equal the fraction of the 100% total each column should be. Being that, we simply set the width to that variable’s value.


Building a Responsive CSS Grid Framework Using Stylus

Furthermore, now that we have a basic understanding of how a CSS grid is built, we can move on to advanced grid development.

As you may know already, Bootstrap uses: col-sm-, col-md- and col-lg- class prefixes to control column sizes across devices.

col-sm-(size) will be set to the column size specified as long as the screen size is above 768px.
col—md-(size) will be set to the column size as long as the screen size is above 992px.
col—lg-(size) will be set to the column size as long as the screen size is above 1200px.

A sketch of a CSS framework like Bootstrap on paper.

Building Media Queries for Responsive Column Sizing

For instance, this is the foundation of any mobile responsive CSS framework – Media Queries. By the same token, this code can be added to the basic framework code to give a fully functional CSS framework much like Bootstrap.

//Setup screen sizes
screen-sizes = (sm md lg)
sm-min-size = 768px
md-min-size = 992px
lg-min-size = 1200px

//Cycle through screen sizes
for screen-size in screen-sizes
@media screen and (min-width: screen-size+'-min-size')
for i in (1..columns) {
.col-{screen-size}-{i} {
col-width = 100%/(12/i)
width: col-width
}
}

In addition to cycling through column sizes, we are now cycling through the screen-sizes as well. Nonetheless, this will be the basis of our responsive media queries.

A boy staring at a pin board full of notes, graphs and sketches.
This can be tricky to understand, but it makes adding screen sizes to your framework easier than ever. For every screen-size array value, simply add the same screen size value + “-min-size”.

In addition, each media query is using the screen-name array value to retrieve the defined {screen-size}-min-size value.

Building CSS Stylesheets From Stylus Using Gulp

If you are a beginner in Gulp and using NPM packages, I recommend first reading Automate Your Tasks Easily With Gulp and Gulp for Beginners. These two articles will give you the basic understanding of the technology to follow through this next section.

Installing the Necessary Gulp Plugins

npm init will generate our package.json file.
On a mac or Linux machine, simply open up a terminal and change directory to your working folder. Then, paste npm i -S gulp-stylus gulp-postcss gulp-autoprefixer gulp-sourcemaps to install all necessary Gulp plugins.

Setting Up the Gulp File for Automation

'use strict';

let gulp = require('gulp');
let stylus = require('gulp-stylus');
let postcss = require('gulp-postcss');
let autoprefixer = require('autoprefixer');
let sourcemaps = require('gulp-sourcemaps');

gulp.task('default', ['slate']);

gulp.task('slate', function () {
return gulp.src('./styl/slate.styl')
.pipe(sourcemaps.init())
.pipe(stylus())
.pipe(postcss([require('autoprefixer')]))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./css'));
});
What These Gulp Tasks Do:
  • pipe(sourcemaps.init()) is telling the Sourcemaps package to intiate.
  • pipe(stylus()) will convert the target styl file to a CSS file. Read more about gulp-stylus.
  • pipe(postcss([require('autoprefixer')])) is responsible for adding piping other CSS generating Gulp plugins to a single CSS file. Notice, the autoprefixer plugin is piped through. Specifically, this plugin simplifies the process of adding the ‘-moz-‘ and ‘-webkit-‘ prefix to stylesheet attributes. Read more about gulp-postcss.
  • pipe(sourcemaps.write('./')) is telling the Sourcemaps package to create a source map for the stylesheet. Consequently, since we are compiling stylus files to CSS there is no way for us to find the error in our code easily using a browser inspector. For this reason, Sourcemaps builds a link to the styl files and instead pinpoints the line of code in the styl file when inspecting instead. Read more about gulp-sourcemaps.
  • pipe(gulp.dest('./css')) is telling Gulp where to place the compiled CSS file. In this case, we are placing the stylesheet in a folder called “css”.

How to Begin Using Our New CSS Framework

Just like linking to the Bootstrap CSS file, we will link to the outputted CSS file saved in the “css” folder. Further, using our generated class names like “col-xs-12 col-md-6” we can begin creating our mobile responsive columns.

Now that you have a basic understanding of how CSS frameworks are made and how to start using Stylus, you can begin adding new features. Make your new framework as simple or advanced as you’d like!

Most importantly, share your new creation so that other web designers may use it and have fun


Feel free to leave a comment and share this article with your friends so that they can learn how to start using Stylus to build their very own CSS framework too!