Flexing the Flexbox muscle

In order to better understand CSS Flexbox let us build our own
basic Grid system. It’s also a good chance to practice separation of CSS code for layout and from styling. When the layout is separated from style, the code becomes less repetitive, easier to compose and reuse. But by no means what we’re doing here is production ready! This is just a small learning exercise. You’re invited to come learn with me.

All grid frameworks out there have their own rules, some kind of API, that is different from each other. Each library has
its own flavor which is natural since everyone has different ways to solve the same problem. You should experiment with a few and see which one you like the most. Our approach is very basic but will be enough for our goals. Let’s define our rules:

  1. No JavaScript
  2. The grid is delimited by a root element. All our classes and markup only work inside of it.
  3. There are only Rows and Columns.
  4. The grid can have Rows. Rows can have Columns. Columns can have Rows.
  5. Rows always take the full available width of its parent container.
  6. Columns share the whole available width of the Row if no size is specified. They shrink and grow as necessary. They only break/wrap if there’s no available space.

We start off the first use case: 2 rows that take the full-width, each with 3 columns that share equally the width available. Let’s write the markup first:

<div class="flex-grid">
  <div class="row">
    <div class="col">
      <h1>Row 1 Column 1</h1>
    </div>
    <div class="col">
      <h1>Row 1 Column 2</h1>
    </div>
    <div class="col">
      <h1>Row 1 Column 3</h1>
    </div>
  </div>
  <div class="row">
    <div class="col">
      <h1>Row 2 Column 1</h1>
    </div>
    <div class="col">
      <h1>Row 2 Column 2</h1>
    </div>
    <div class="col">
      <h1>Row 2 Column 3</h1>
    </div>
  </div>
</div>

Working with invisible elements is not that easy so let’s add some visual cues so we can track our progress. A few borders and background color will do the trick:

.flex-grid {
  background-color: #ddd;
}

.flex-grid .row {
  border: 1px dotted red;
  box-sizing: border-box;
}

.flex-grid .row .col {
  border: 1px dashed blue;
  box-sizing: border-box;
}

Time to turn on the Flexbox! Just add display: flex; to .flex-grid and Boom! The layout is totally wrecked now but we’ll adjust it step-by-step.

Since our grid can only have Rows as direct children, and every row must always be on top of each other, we have to add flex-direction: column; to .flex-grid. Wait, what!? Rows as columns?! Yep. Not very intuitive at first glance. That’s why this exercise is important: it will put us out of our comfort zone and force us to really grasp the theory and put it into practice.

So what’s going on here?

When we set the flex-direction to “column“, we’re telling that we want every direct child element of the flex container to be displayed on top of each other to form a column/stack. Which is what we want: rows stacked on top of each other occupying the whole width.

Unfortunately, the columns are behaving just like Rows too. We want that all columns of a row share the available width by default. This also means that the columns must appear next to each other, in a line. We could achieve this by setting display: inline; or float: left; to the columns … but that’s not Flexbox. Since the layout of the Columns is ruled by the parent container, setting display: flex; to .flex-grid .row does one of the tricks: Columns in a row. But now the Columns only occupy the space required by its contents. To fix this we must tell the Columns to grow as much as they can by setting flex: 1; to .flex-grid .row .col. Uh la la!

Things are starting to look good but let’s first try some nesting. Replace the contents of the first Column of the first Row with the following snippet.

<div class="row">
  <div class="col">
    <span>Inner Row 1 Col 1</span>
  </div>
  <div class="col">
    <h4>Inner Row 1 Col 2</h4>
  </div>
</div>
<div class="row">
  <div class="col">
    <p>Inner Row 2</p>
  </div>
</div>
<div class="row">
  <div class="col">
    <span>Inner Row 3</span>
  </div>
</div>

Beautiful, it works wonders out of the box! This truly shows the potential of Flexbox. Let’s try to add some width modifier to our columns so we can have so more control over our layouts. We’ll skip responsive breakpoints for now and apply the widths for all sizes:

  • .all-20: 1/5 (20%)
  • .all-25: 1/4 (25%)
  • .all-33: 1/3 (33%)
  • .all-50: 1/2 (50%)
  • .all-60: 3/5 (60%)
  • .all-66: 2/3 (66%)
  • .all-75: 3/4 (75%)

Another important detail: when we specify the column width, that’s the min and max width it should have -a fixed proportion. So we add the following selectors and rules:

.flex-grid .row .col.all-20 {
  max-width: 20%;
  width: 20%;
}

.flex-grid .row .col.all-25 {
  max-width: 25%;
  width: 25%;
}

.flex-grid .row .col.all-33 {
  max-width: 33%;
  width: 33%;
}

.flex-grid .row .col.all-50 {
  max-width: 50%;
  width: 50%;
}

.flex-grid .row .col.all-60 {
  max-width: 60%;
  width: 60%;
}

.flex-grid .row .col.all-66 {
  max-width: 66%;
  width: 66%;
}

.flex-grid .row .col.all-75 {
  max-width: 75%;
  width: 75%;
}

So if we add .all-25 to Column 2 of Row 1, it shrinks to 1/4 of the Row width as expected and the other two Columns grow. But if instead of .all-25 we apply .all-75 it doesn’t work, they all occupy 1/3 of the width. This is a bit trickier.

When we set flex: 1; it’s actually a short-hand for setting flex-grow: 1; flex-shrink: 1; flex-basis: 0%; The most important detail being flex-basis: 0%;. This means that the element will not enforce its min size. And since all other Columns have the same rule, the result is that they only grow to the max width which is equally divided. To make sure the Column has the width it was supposed to have, we got to set flex-basis: 100%; to all width modifiers. And now it’s working!

But what happens when we apply .all-25 to Column 1 of Row 1? The first two Columns (1/4 + 3/4 = 1) should occupy 100% of the Row’s width but why the hell Column 3 is still in the same Row?! Why didn’t it break to the second line? Well, that’s because we didn’t tell the Row to allow it. And to do it we must set flex-wrap: wrap; to .flex-grid .row.

Another interesting feature we can add to our Flexbox grid system is the ability to align Columns. And who controls the alignment? The parent container: Row! We can create the following modifier with the Flexbox property justify-content to put Columns at the horizontal center of the Row:

.flex-grid .row.hor-center {
  justify-content: center;
}

It’s important to note that this only works if the Columns have a defined width. How can you know what’s the center of the Row if the Column is occupying the whole width? Once the Column has a width, say 50%, the Row can calculate how much space is left and position the Column at its horizontal center.

But you want to put the Columns at the vertical center of the Row, right? For that, we need a different Flexbox prop: align-items. If justify-content works by placing elements on the X/horizontal axis, align-items works on the Y/vertical axis. So we add a new Row modifier to center columns vertically:

.flex-grid .row.vert-center {
  align-items: center;
}

There you go! A super basic base for a grid system implemented with Flexbox. Just enough features so we can practice some core concepts and solidify them in our CSS knowledge base.

The whole CSS for our basic Flexbox grid system:

.flex-grid {
   background-color: #ddd;
   display: flex;
   flex-direction: column;
 }

.flex-grid .row {
   border: 1px dotted red;
   box-sizing: border-box;
   display: flex;
   flex-wrap: wrap;
 }

.flex-grid .row.hor-center {
  justify-content: center;
}

.flex-grid .row.vert-center {
  align-items: center;
}

.flex-grid .row .col {
   border: 1px dashed blue;
   box-sizing: border-box;
   flex: 1;
   padding-right: .5em;
 }

.flex-grid .row .col:last-child {
   padding-right: 0;
 }

.flex-grid .row .col.all-20 {
   flex-basis: 100%;
   max-width: 20%;
   width: 20%;
 }

.flex-grid .row .col.all-25 {
   flex-basis: 100%;
   max-width: 25%;
   width: 25%;
 }

.flex-grid .row .col.all-33 {
   flex-basis: 100%;
   max-width: 33%;
   width: 33%;
 }

.flex-grid .row .col.all-50 {
   flex-basis: 100%;
   max-width: 50%;
   width: 50%;
 }

.flex-grid .row .col.all-60 {
   flex-basis: 100%;
   max-width: 60%;
   width: 60%;
 }

.flex-grid .row .col.all-66 {
   flex-basis: 100%;
   max-width: 66%;
   width: 66%;
 }

.flex-grid .row .col.all-75 {
   flex-basis: 100%;
   max-width: 75%;
   width: 75%;
 }

This is a very limited implementation and we can still achieve some interesting results:

Keep on honing your skills while having some fun.
Cheers!

Flattr this!

Still having fun with Flash

I would like to share some little piece of code that I wrote recently in AS3. It’s been quite a while since last time I did anything with Flash technology and I must admit that I had loads of fun. Maybe too much. I still can’t believe that this technology is dying in favour of HTML considering only the technical parts. I really support what the Web and all it’s technology represents and how much it empowers people who care to learn it. I really get inspired by the folks at Mozilla and how hard they work to keep the web an open competitive place for everyone.

But dealing with browser glitches and wimps, render engines optimisations, thousands of mobile phones, hunting for bugs on hundreds of CSS rules and so on is just a freaking nightmare! Specially when you are on the frontline on release day. It’s totally doable, I get paid really well to do it, but it is not fun. There’s also that dread that every single day there’s a newer technology supposedly much better the one you’ve been learning on the past 24h. There are so many frameworks and libraries and plugins to handle every device/browser/os. Or maybe it’s your client/project/boss that demands some specific technology. Flash and Java have the same problem but it’s much much smaller. Instead of choosing between 5 Flash libraries for animating something on the screen, you have to choose between 15 in HTML. By the way, those are fictional numbers just so that you can feel the dread. Or is it really?

In my opinion, Flash will not go away anytime soon. It changed too many things, it runs in too many environments, it works for many projects, there are too many experts and tools and books and blogs and knowledge. You can’t kill something this big that easy. And it’s also a lot of fun!

Enough sentimental blabber! I implemented a small super efficient image scroller using a few 2D rendering tricks of the platform. Using Stage3D would probably give even better results but it’s out of my reach for now. This little program works really well for navigating huge panoramic images smooooothly.  Check it out for yourself. The PanoViewer Demo is a release build so make sure to use a Release Flash Player plugin. You can get a really amazing effect if your monitor has very low response time and delay. My monitor failed miserably on these tests so the effect beauty is really diminished.

There are two projects: PanoViewer and Panomax.

PanoViewer

It’s the Flash application that handles the logic of loading assets, rendering buttons and initializing the Panomax instance. It’s important to notice the SWF metadata tag with the frameRate = “1” parameter. This specifies the frame rate of the application, in frames per second. The default value is 24. Lowering it’s value gives the runtime a much longer Elastic Racetrack , roughly 1/2 second for each phase, which also means lower loads on the system. This is a key concept to understand and we’ll exploit it.

The CachingImageLoader is a very simple external image loader with very basic caching functionality and tries to deal with Security Sandbox details. The CTAButton – Call To Action – is a custom button class with different style and it makes sure the text label always fits its boundaries.

Panomax

Here’s where the magic happens. The loaded panoramic image (Bitmap) and other parameters are passed to the Panomax instance. It calculates all boundaries, configure the interactions and starts a Timer. On the TimerEvent handler function that all matrix transformations are calculated and where a part of the panoramic image is painted on the canvas. If it was not obvious yet, painting a small portion of an image is much faster than moving a gigantic image around. We just need 1 Matrix object and 1 call to BitmapData.draw(…). Things start to get very interesting when we add the horizontal looping (function onTimerXLoop). To help us understand how it works I made this schematic:

Panomax schematics

You have to start from the middle, where gTx = 0. If you go reading up, gTx increases and the image is moving to the left. If you go reading down, the image is moving to the right. Let’s not forget that Matrix transformations (tx, ty) signs means that negative is to the left and positive is to the right. Here’s an awesome Matrix transformation tutorial if you are not familiar. Since the image loops horizontally, the are some states in which it needs to be rendered twice: one on the far left and the other on the far right. For that we use 2 Matrix objects and 2 BitmapData.draw(…) calls which is the heaviest state for the system.

There are some clever tricks that we can do with the transformations of the matrixes in order to use simple formulas. For instance, once the left edge of image A moves out on the right edge of the canvas, it looks exactly like image B with its right edge on the right edge of the canvas which also looks exactly like image A with it’s right edge on the right edge of the canvas. So we can swap/render B with A! Clearly, from my code, I couldn’t figure out the simple formulas so I ended up with complicated ones.

Now, for the last trick, we need to analyse just 1 line of code: e.updateAfterEvent(); // for immediate rendering! To understand this you really have to dominate the concept of the Elastic Racetrack that I mentioned earlier. With the app frame rate reduced to 1, our async code (the TimerEvent handler function) has more time to run and most probably won’t interfere with the other phases of the racetrack. So the Matrix calculations are done, the images are rendered on the canvas but the application frame is not updated yet because the rendering phase is still many milliseconds away. Thus we force the rendering with plenty of time to do so. With enough time for both racetrack phases, what we get is butter smooth scrolling performance!

This is it! I hope you liked it this tutorial. The code is on Github so go ahead and study and fork it!

Panorama Image Credits

  1. SonyCenter 360 panorama: Homepage, Download, Author: François Reincke

    Full resolution: 3,500 × 1,096 pixels, file size: 922 KB, MIME type: image/jpeg, License: CC-BY-SA 3.0.

  2. Trafalgar Square: Homepage, DownloadAuthor: David Iliff alias DiliffFull resolution: 9.932 × 2.075 pixels, File size: 5.67 MB, MIME type: image/jpeg, Camera location: 51° 30′ 29.39″ N, 0° 7′ 41.31″ W, License: CC-BY-SA 3.0.
  3. Lac de Joux: Homepage, Download,Author: Lausanne De Suisse alias 100zaxFull resolution: 6.000 × 697 pixels, File size: 759 KB, MIME type: image/jpeg, Camera location: ??? N, ??? W,License: CC-BY-SA 3.0.

Flattr this!