Ville Karavirta

May 25, 2011

CSS3 and AV revisited (with flexible box layout)

In the first post about CSS3 and algorithm visualization, I had demos showing how to animate sorting algorithms using CSS3 transforms. Yesterday, when watching CSS3 First Look on Lynda.com, I learned about the CSS3 Flexible Box Layout Module and wanted to give it a try and improve the previous animations.

Flexible Box Layout

The flexible box layout gives an excellent way to control the layout and ordering of elements on a page. All in all, it’s really flexible. To give an example, let’s work with the following HTML. 

<div id="container">
  <div id="box1">Box 1</div>
  <div id="box2">Box 2</div>
  <div id="box3">Box 3</div>
</div>

Now, without any styling, this would become a page where the divs are vertically on top of each other. With just one line of CSS3 magic, we can change that:

#container  { display: box; }

Actually, we need at least three lines until the specification is ready and vendor prefixes are dropped:

#container {
  display: -webkit-box;
  display: -moz-box;
  display: box;
}

This will arrange the boxes horizontally next to each other (see the demo, example 2). The feature I was most interested in related to the sorting algorithm animation is the box-ordinal-group property. It allows to change the order of the child elements inside the box. To give you an example, the following CSS3:

#box1 { 
  -webkit-box-ordinal-group: 2;
  -moz-box-ordinal-group: 2; 
  box-ordinal-group: 2;
}
#box2 {
  -webkit-box-ordinal-group: 3;
  -moz-box-ordinal-group: 3;
  box-ordinal-group: 3;
}
#box3 {
  -webkit-box-ordinal-group: 1;
  -moz-box-ordinal-group: 1;
  box-ordinal-group: 1;
}

would change the boxes to be in order box3, box1, box2 from left to right (view the demo, example 3).

Visualizing Sorting Algorithms

One of the problems with the original CSS3 algorithm visualizations was the calculation of pixels when translating the elements to animate array item swaps. The box model seems like a great solution for replacing the pixels with just changing the box-ordinal-group property.

After creating a simple test case, I realized that it did not work as I suspected. The elements changed places, but no smooth animation was shown. After spending some time trying to fix my CSS I turned to Google. To my disappointment, it wasn’t my code that was broken. Nor was it the browser. The box-ordinal-group just isn’t one of the animatable properties according to the CSS3 Transitions specification.

So, to sum up the experiment: flexible box model could be used to visualize sorting algorithms, if no smooth animation is needed. In modern browsers, that is. According to caniuse.com, browsers that support this currently are Firefox 3.5+, Safari 3.2+, and Chrome 9.0+. In addition, Mobile Webkit on iOs and Android support it.