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