I love CSS flexbox - The Ultimate layout tool

Why I love CSS Flexbox - The Ultimate layout tool

There are some of us Front End Developer who’s beginnings have come from the heart of some area of design. For myself it was Graphic Design. There is a great amount of joy found in creating a new website design and seeing it come to life in a browser window.

What brings even more joy, is when you learn how to code and you bring your own designs to life, promoting yourself to a Creative Front End Web Developer. What I used to find challenging was, converting a wonderfully crafted unique design into, HTML and CSS. It seemed that the more I tried to use creative web design layouts, the more restrictive the code appeared to be. I can re-call early in my web development career, feeling my heart sink when being presented with a less than boxy design by non-coding Designer (Yes there was a time we had to use images for rounded corners!).

Thankfully those times are coming to a close. The CSS specifications is maturing and providing developers with tools that will make that process of, converting web design layouts from PSDs to HTML & CSS a lot more easier.

One of those tools is the Flexbox model. It provides some immensely useful CSS rules that will aid converting PSD designs to HTML. As well as helping make your development process easier, it has added benefits for on-going maintenance when inevitable changes have to be made.

But how did we get here, what tools did we have to use in CSS’s past and why is Flexbox a tool worth adopting into your coding toolbox?

How we used to create HTML / CSS layouts

HTML Tables

Before the magic of css 2.0 was bestowed upon us, early developers used good old tables to structure layout of webpages. However more complex layouts required things such as nested tables.

As well as being fiddly to develop, maintenance was not a friendly experience. Interestingly, today HTML emails still predominantly use tables to control their layout.

CSS Floats

CSS floats came and was then widely adopted as the tool to help you control the layout of your pages. No longer did you have to fight with tables, instead you had the joy of fighting with floats, clear fixes and percentage widths and grid systems.

Throughout this period We have had seen some really useful css frameworks developed to help coding webpage layouts easy. 960 grid anyone?

Why use CSS Flexbox?

Typically the role of a Front End Developer is to take a design layout which has been created by a Designer and convert that design into HTML. The expectation from the Designer is that the layout is replicated as pixel perfectly as possible.

But creating layouts, Developers have been limited by the tools that have been available at the time. The popular methods of creating layouts with tables or floats had or have become so mainstream, that you can be forgiven for overlooking the original intended purpose of tables and floats.

Occasionally I find myself using the Mozilla Developer Network documentation to help me find solutions to CSS and HTML challenges. If this is something that you have briefly checked, I encourage you to invest some time browsing it many pages. From reviewing the docs we can see what the intended purpose of HTML elements and CSS rules are.

From reading the documentation, we can see that <table> was intended to be used to display data.

The HTML <table> element represents tabular data — that is, information expressed via a two-dimensional data table.

MDN Tables

Also taking a look at the specifications of floats are:

The float CSS property specifies that an element should be placed along the left or right side of its container, where text and inline elements will wrap around it.

MDN CSS Floats

Even though we have used tables and floats outside of their original intended purpose, it also draws light as to why coding CSS has been a hacky and sometimes painful process.

But ultimately, what we have been waiting for is a tool that is designed specifically for creating layouts. Introduce Flexbox, the tool created specifically with layouts in mind.

CSS Flexible Box Layout is a module of CSS that defines a CSS box model optimized for user interface design. In the flex layout model

All hail the mighty FLEXBOX!

What benefits does CSS Flexbox have?

Firstly flexbox is well supported across the main modern web browsers, which answers the question of “Can I use it”. And when it comes to it’s core strengths, flex box helps with such common CSS/HTML layout problems like:

  • Equal height columns
  • Equally spaced items without calculations
  • Vertical Aligning of elements
  • Grids
  • Reflowing layouts without media queries (Say Whaaaat!)
  • Graceful degradation for the unknown

In turn to you, as the Front End Developer, these benefits mean less caveats for you to keep an eye on and help you speed up the development of design layouts.

You may find that your CSS is going to become part of a part of a bigger CMS. With Flexbox, you are given some protection against unintended variables breaking your layout.

What about responsive design?

Once upon a time the standard screen resolutions you built your website’s around were mobile, tablet and desktop. And still today you may design or have been supplied design layouts for the triad. You may have had the experience of, coding a HTML layout that looks perfect in both media queries for @768px (iPad) and @320px (iPhone 5) only to find out that at 414px (iPhone 6S) the layout looks a little off.

Today there are so many screen resolutions to cater for, and in seeking the path of least resistance my point of view has changed somewhat. This may be a controversial way of thinking, but in some layout designs cases, due to the re-flow features of Flexbox, you could omit the use of media queries. In the rest of cases, rather than using set screen resolutions to set up media query breakpoints, restrict the use of media queries only to adjust the Flexbox layout when the design is considered to be at its breaking point.

Flexbox VS Floats

This piece would not be complete with out a little code comparison between Flexbox and the more commonly used floats. I have taken a simple pricing table design that you would expect to see when signing up for a service. In both examples we are able to convert the design to HTML & CSS using both Flexbox and floats.

Floats in CSS

/* Added on styles - floats css 2.0 */

.container{
    padding: 5px;
}

.pricing-table{
    width: 32%; /* Set items width */
    float: left; /* Set the positioning */
    /* now they dont fit - so ensure we are using box model box border */
    box-sizing: border-box;
}

/* Lets add a margin to the pricing tables */
.pricing-table{
    margin-right: 2%; /* Becasue we use % to calculate the gutter width */
}

/* We have a broken layout, lets fix this */
.pricing-table:last-child{
    margin-right: 0;
}

/*
    We need to vertically align the Price Level
    A span tag was needed around the text in order to move it
*/
.pricing-table__level span{
    position: relative;
    top: 50%;
    transform: perspective(1px) translateY(-50%);
    display: block;
}

/* Adding media queries to stop the block being squashed */

@media (max-width: 768px){

    .pricing-table{
        margin: 0px;
        margin-bottom: 20px;
        width: 100%;
    }

    /* For cleaning up the layout */
    .pricing-table:last-child{
        margin-bottom: 0;
    }

}
                    

Flexbox in CSS

/* Added on styles - flex css 3.0 */

/* Add flex box top the parent container */
.container{
    display: flex;
    justify-content: space-between; /* equally spaces out the tables */
    flex-wrap: wrap;
    padding: 5px;
}

.pricing-table{

    flex-basis: auto;
    flex-grow: 1;
    display: flex;

    flex-direction: column;
    align-items: stretch;
    margin: 5px;
}

/*
    We need to vertically align the Price Level
    No span tag was needed :)
*/
.pricing-table__level{
    display: flex;
    justify-content: center;
    align-content: center;
    flex-direction: column;
}
                    

The things that you will notice about the Flexbox approach is, on top of the base styles, there is less code needed. There are also no media queries used, but resizing the browser window all the way down to mobile screen width, the blocks reflowing around the page.

Flexbox helps your maintenance

Typically, websites are evolving entities. After a website site goes live, the needs of the business change and that requires some adjustments to the CSS code base.

In these moment this is where the magic of Flexbox really shines. So using our example of the pricing tables, inevitably the business needs require modification. You may experience that change will come directly to you as the Frontend developer In our pricing table, those changes are:

  1. A new price level block is added
  2. Higher price levels have more rows of content
  3. Ensuring the subscribe buttons stick to the bottom of the block

1 Adding a new price level

Adding a new block to our floats breaks our layout. Changing the number of blocks in the layout means we are required to recalculate the percentage widths of the columns.

/* FLOATS */
 .pricing-table{
	width: 23.5%;
	padding: 10px;
}

Also bear in mind, this is only for when we change the amount of columns from 3 to 4. For more or less columns, we would need to recalculate the percentage widths. One may argue because you may not know how the needs of the project may change, that this is where a css grid framework would come in. But it’d be nice to create CSS in a world that didn’t have to rely on extra code for those unknown situations.

For Flexbox there is not really any need to add new CSS rules, as the content will automatically resize the divs. If you resize your broswer window you will also see the items are auto magically reflowed around the page. Neat huh!

2 Add more price level information

When you add more rows of content to the any of blocks, for our floats, it creates the issue of uneven columns. Floats are removed from the flow of the page. This means they aren’t able to correlate to other siblings sharing the same container space. The easy fix in this scenario is the give the blocks fixed heights.

/* FLOATS */
 .pricingtable{
	min-height: 550px;
	position: relative;
}

A downside to this approach is, if changes are again required at a later date, more tweaking of our floats are required.

With Flexbox, well. The nature of Flexbox is to have a consistent effect on all children so, equal height columns are already taken care of.

3 Sticking the price to the bottom of the block

Once we have added new content to the price level, you will note that the price and Subscribe buttons need to be aligned.

For our floats, we need to use some css hackery to get the result that we desire. Once again it relies on removing our .pricing-table__price div out of the page flow by use the position absolute rule.

/* FLOATS */
.pricing-table{
	position: relative;
}

 .pricing-table__price{
	position: absolute;
	bottom: 15px;
	left:  0;
	width: 100%;
}

To achieve the same result with flexbox, we can tweak the .pricing-table__price div by adjusting it to:

  • Expand the price div to fill the remaining space
  • Make the price div display its child items as flexbox
  • Align the children items to the bottom using flex-end
/* FLEXBOX */
.pricing-table__price{
	flex-grow: 2;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
}

Flexbox, making your coding life more flexible.

As you can see working with floats requires some additional work to get the layouts that you desire. You can imagine that having to deal with this on a regular basis, it makes dealing with CSS more painful an experience than it really ought to be. Due to not having a suitable tools available in the CSS specification, these hacks have been born out of necessity, by some very clever people.

Flexbox removes the need for css hacks. Of the 3 changes that were required will only needs to get our hands dirty again in one case. Investing some time in getting to grips with the flex box model, will pay it’s returns in the form of a more pleasing coding experience and better maintainable code.


Contact Me


By email: nutyga[at]gmail.com

You can also contact me via my LinkedIn profile link below