Sep 22, 2014 - 0 Comments - Basics, CSS, HTML, Programming -

Squaring things off

As a developer its not uncommon to receive designs to build that square-off page elements at the bottom.  Where, say, content and sidebar, or a range of columns have been designed to be level at their base. Most frequently these are from print designers, now less familiar with markup (which was originally a printer’s medium).

The key problem is this. For two elements to match in height they must both extend to the foot of their containing element. To do that, the container needs to extend to the height of the longest inner element, and siblings need to extend to 100% height of the container.

Now it’s possible in pure CSS to have a parent div match the height of floated inner elements, either with a clearfix kludge, overflow:hidden, or setting heights explicitly. Each has its drawbacks, and only setting explicit heights enables floated divs to extend the full height of their parent using a height:100% declaration.

So what’s the solution?

There have been three key methods tried in an effort to meet the challenge of squaring off designs:

Image backgrounds

Clever use of background images can make it appear a sidebar is the same height as its sibling content. For a long time, until designs were required to be responsive, this was the most common solution. These days though, with page elements morphing to any width or height, such careful crafting of background images is not a sustainable solution.

Explicit Height / Min height

When pages are a set size – where content, text and element sizes are precisely defined and controlled, it is possible to set all sizes exactly. Even in 2015 we still get clients requesting designs with precise sizing, on the assumption their content won’t change. Explicit sizing may solve some layout issues, but the administrative overhead when content does change make the technique one to avoid.

Javascript/Jquery

In the end the most effective, sustainable and simple solution to balance columns is via javascript. My library of choice is Jquery, and the simplest, most versatile method I’ve built is this snippet, which uses apply and map to even the heights of all elements with the same class, in this case, the class ‘even’:

$('.even').height(
  Math.max.apply(null, $('.even').map(function () {
    return $(this).height();
  })
 );
);

Ultimately the need for javascript to achieve what should be a simple task is sad, but pretty common. Maybe one day, when CSS4 appears perhaps, 100% height on floated divs and box models which reliably allow parent elements to expand according to their children will become a reality, but until then, the javascript solution is the way to go.