CSS scale height to match width - possibly with a formfactor

Steen picture Steen · Jun 28, 2012 · Viewed 156.3k times · Source

I have implemented a GoogleMapsV3 map in a twitterBootstrap basic responsive design site.

But my question is quite simple: i have:

<div id="map"></map>

and

#map{ width: 100%; height: 200px }

I'd like to be able to change the height to a form factor. Like in this "in my dreams CSS"

#map { width: 100%; height: width * 1.72 }

I have tried leaving out height, setting to auto, and all sorts of persentages - but only to make the div collapse on me always.

I have no problem writing a js-solution, but hope for a simple cleancut CSS solution, possible CSS3

If not possible, what would be the optimal way to js me out of this?? (timers, events...or the like)

Answer

banzomaikaka picture banzomaikaka · Jun 28, 2012

Here it is. Pure CSS. You do need one extra 'container' element.

The fiddle

(tinkerbin, actually): http://tinkerbin.com/rQ71nWDT (Tinkerbin is dead.)

The solution.

Note I'm using an 100% throughout the example. You can use whichever percentage you'd like.

Since height percentages are relative to the height of the parent element, we can't rely on it. We must rely on something else. Luckily padding is relative to the width - whether it's horizontal or vertical padding. In padding-xyz: 100%, 100% equals 100% of the box's width.

Unfortunately, padding is just that, padding. The content-box's height is 0. No problem!

Stick an absolutely positioned element, give it 100% width, 100% height and use it as your actual content box. The 100% height works because percentage heights on absolutely positioned elements are relative to the padding-box of the box their relatively positioned to.

HTML:

<div id="map_container">
  <div id="map">
  </div>
</div>   

CSS:

#map_container {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
}

#map {
  position: absolute;
  width: 100%;
  height: 100%;
}