CSS: Keeping a div's height relative to its width

Akshaya Shanbhogue picture Akshaya Shanbhogue · May 14, 2013 · Viewed 16.9k times · Source

My question is very similar to this question: CSS: 100% width or height while keeping aspect ratio?

I have a div whose position is fixed. The width of the div must be 100% and its height exactly 1/6th of its width. Is there a -webkit-calc() way of doing this?

Note: JS solutions are not preferred as a zoom/orientation change can affect the width/height.

Answer

Mathijs Flietstra picture Mathijs Flietstra · May 14, 2013

Is this what you are after? I'm not using -webkit-calc() at all. I've inserted a 1px by 6px image into a outer div which has position: fixed applied to it, and set the image to have a width of 100% and position: relative. Then I have added an inner div which is absolutely positioned to be as high and wide as its ancestor.

Now you can change the width of the outer div, and the images' width: 100% setting will ensure that both the outer and the inner div's are guaranteed to always have a height equal to 1/6th of their width (or at least as close to exactly equal as it can get, the heights will be rounded off to the closest whole number of pixels). Any content could go inside the inner div.

HTML

<div>
  <div></div>
  <img src="https://dl.dropboxusercontent.com/u/6928212/sixbyone.png" />
</div>

CSS

html, body {
  margin: 0px;
  padding: 0px;
}
div {
  position: fixed;
  width: 100%;
}
div > div {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;      
}
img {
  width: 100%;
  display: block;      
  position: relative;
}

Here's a jsFiddle showing the requested behaviour.