Scaled/Proportional Content with CSS and JavaScript

The web is a fluid place. Different sized screens, yadda yadda yadda. Fortunately for us, the web is ready for it. Text wraps. CSS gives us control over how to size things. What we don't get (easily, anyway) is a way to scale whole element (and it's children) proportionally—retaining its exact layout as it changes size.

We can do it though.

Proportional scaling of a *container* is fairly easy

Uncle Dave's Ol' Padded Box:

.parent {
  height: 0;
  padding-bottom: 56.25%; /* 16:9 */
  position: relative;

Then if you want content inside, you can absolutely position a covering container inside:

.child {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;

This can be quite useful for things like images, containers that can independently scroll, or containers with so much spare room that it can handle dramatic changes in shape.

If the content of this container was, say, an image, it works great!

But things aren't so happy if there are a bunch of HTML element children just doing what regular ol HTML elements do.

Proportional scaling of everything

Let's say this is the kind of thing we're after:

CSS alone can't really do this. But CSS is still the answer! transform: scale(); is what we need. It scales things perfectly proportionally. We just need to give it a number to scale it by, and that scale we can figure out with some JavaScript.

The trick is:

var scale = Math.min( 
  availableWidth / contentWidth, 
  availableHeight / contentHeight 

Here's one possible approach to that, using jQuery and jQuery UI Resizeable (because that's easy and comfortable for me):

See the Pen Resize with Scale by Chris Coyier (@chriscoyier) on CodePen.

Other ways...

SVG does this all by itself. Let's cover this in an article really soon. I have some things to say. ;)

Also, you may be able to size everything with vw/vh units maybe, but that sounds like a pain in the butt and a whole lot of magic numbers.

It's probably a bit rare that you'd need this

The reason I'm all into this idea is because I noticed that embeddeddable slide decks from work like this.

That's a perfect use case. gives you a fixed size canvas to create your slides on, which completley makes sense. Then those slides can scale up if needed, to present in a larger space. Or scale down to fit on smaller screens (like if you embed them into a blog post with a narrow content column or view on a mobile device).

I think about Embedded Pens as well. Sometimes people design Pens to work in a larger area, and the design breaks down when it's embedded. I could use this to proportionally resize the guts, but only as much as needed to fit.

Maybe iframes? Probably mostly third-party or user-generated stuff, and in situations where the proportion matters, otherwise, carry on with regular RWD action.