Responsive Squares Without Flexbox

Posted on: November 21st, 2013

I was thinking about the Metro UI the other day, in all it’s sexiness (I’m an XBox guy, #sorrynotsorry) and I realized that I had no idea how to make responsive squares. Sure there’s flexbox, but just take a gander at the flexbox page on caniuse.com and you can see why this is not yet the optimal solution.

So, where do we begin. Well, we know that we can get widths set up, but setting the following does not yield a square:

.small {
   height: 25%;
   width: 25%;
   display: block;
}

Especially with no content inside that does absolutely nothing for you. How do we fix that. Well, a bit of hackery with JavaScript could calculate the width on resize and adjust the height accordingly, sure that’s a solution. But how would we do it with just CSS? I stumbled across this article from Nathan Rohler that gave me a pure CSS solution.

By adding another div inside your .small div and by giving .small some padding on the bottom, you can pull off a responsive square.

.small {
   padding-bottom: 25%; 
   width: 25%;
   display: block;
}

.small div {

}

If you’ve got content in that new div, you may not see it as a square, but when absolutely positioning the inner div (thus the position:relative; previously) everything lines up properly.

.small div {
   position: absolute;
   top: 0;
   left: 0;
   color: #fff;
   padding: 10px;
}

Check out my codepen, which is a bit prettified.

See the Pen Responsive Squares by John Hartley (@johnbhartley) on CodePen

That’s pretty much it. You have the base of your responsive squares and can start using them responsively without flexbox. This is definitely a case where you’d have to be wary of your media query sizes as it can be a bit hairy since your squares will get smaller and smaller. Pay close attention and bend it til it breaks. Once it does, take note and add a media query. Re-arranging is definitely a good option on smaller screen sizes.

I haven’t done much cross-browser testing, but I can see there being issues. If you find something before I do, be sure to leave a comment below.

previous post: Setting Up WordPress Multisite next post: Optimizing SVG Images with Node.js