Over a million developers have joined DZone.

CSS from the Definition Up: Keeping Boxes Square

DZone's Guide to

CSS from the Definition Up: Keeping Boxes Square

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Today I came across a slick little HTML5 tool called Fluid Squares -- keeps squares square even within a fluid layout. Neat, but pretty darn specific. (Though maybe not all that specific, if the grid layout lies at the heart of much 20th-century design, and perhaps enjoys deep roots in human visual processing.)

But Fluid Squares is now in version 2, and the difference between v1 and v2 is what really caught my eye.

Version 1 uses transparent images to maintain square proportions -- which seems a little old-school hackish (remember invisible spacer gifs?).

Version 2 is much improved by Marco Lago's careful interpretation of the CSS box model.

Here's how simple it is to maintain equal measurement along two dimensions:

It is possible to make full CSS fluid squares without images hack or javascript workarounds? YES! Just think how paddings (and margins) works in the box-model definition. If the vertical paddings (and margins) are specified in percent (%) values the size is a percent of the width of the containing element.

So if you write:

width: 50%;
height: 0;
padding-bottom: 50%;

you get a fluid square box with only a three row CSS declaration.

The relevant spec passage isn't actually located in the box model definition. Instead, this text:

Specifies a percentage width. The percentage is calculated with respect to the width of the generated box's containing block. If the containing block's width depends on this element's width, then the resulting layout is undefined in CSS 2.1.  

is contained in a subsection of the 'Visual formatting model details' chapter, right after the definition of 'containing block'.

This isn't just smart CSS; it's drilling down to the exact specifications, and turning an element's basic definition into an elegant, real-world solution.

You can find plenty of great CSS snippets on the web, but not too many grow so immediately from the definition of the element itself. Reading specs carefully pays off, I guess, even for very small (but, for heavy gridders, quite significant) applications.


Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}