CSS from the Definition Up: Keeping Boxes Square
Join the DZone community and get the full member experience.Join For Free
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:
So if you write:
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.
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.
Opinions expressed by DZone contributors are their own.