Uncle Dave's Ol' Padded Box

Recently on ShopTalk, we were asked about our favorite CSS tricks. I thought I'd share a new trick I've been playing with in my RWD workflow.

Inspired by Elliot Jay Stocks’ article “Better Background Images for RWD” and comments therein, I combined 2 of my favorite concepts for great success: Thierry Koblentz’ Intrinsic Ratios + background-size: cover.

How to use Uncle Dave’s Ol’ Padded Box

<!-- http://yaccessibilityblog.com/library/aria-fix-non-standard-images.html -->
<div id="meowmeow" role="img" aria-label="Kitty Cats"></div>

<style>
  #meowmeow {
    background: url(http://placekitten.com/720/405/) no-repeat center center;
    background-size: cover;
    height: 0;
    padding-bottom: 56.25%; /* 16:9 */
  }
</style>

It’s an empty DIV1 with a standard background-image, except that it has a height of zero and a padding-bottom of 56.25%. Similar to how FitVids.js works, the aspect ratio is maintained by percentage padding based on the width of the parent element. Now, you have a DIV and you could drop a layer of text into it.

Flexible Implementation

Responsive Images are a bit of a deal, but becuase Uncle Dave’s Ol’ Padded Box is just CSS, you can sorta make this thing do whatever you want. I’d stay away from targeting specific devices, but for example:

<style>
/* What if someone visits using an iPad? */
@media screen and (min-width: 768px) {
  #meowmeow {
    background-image: url(cat-using-iPad.gif);
  }
}
/* ZOMG! WUT ABOUT RETINAZ D00D!?? */
@media (min-width: 768px) and (min-device-pixel-ratio: 1.5) {
  #meowmeow {
    background-image: url(cat-using-iPad@2x.gif);
  }
}
</style>

Advanced Usage: Change the Aspect Ratio

If your design gets weird or you need to pay attention to hierarchy, you can change the aspect-ratio/auto-cropping of the image with just a little CSS:

<style>
/* The place where every responsive design gets a little weird */
@media screen and (min-width: 480px) and (max-width: 700px) {
  #meowmeow {
    padding-bottom: 75%; /* 4:3, Dribbble-style */
  }
}
</style>

You gain a bit more flexibility when using a background-image rather than an IMG tag. I realize an empty DIV isn’t ideal for every situation, but there are a few advanced techniques you can do (hopefully will blog about those later).

Browser support :)

The obvious limitation is the dependency on background-size: cover. Great news is background-size is supported in all modern browsers and matches media query support exactly. The only place you might experience problems is using a media query polyfill for older browsers.

High-Contrast Mode :(

Sadly, even with ARIA role=img all background-images are stripped out in Windows’ High-Contrast Mode. This may be a dealbreaker for you if your image is a bonafide content image.

  1. If your image is just a decorative background, then you might not need the ARIA role stuff.

comments powered by Disqus