Scaling div width depending on height

theorise picture theorise · Oct 3, 2013 · Viewed 7.9k times · Source

I want to have a site that is 100% of the height of the browser at all times, with the width scaling with an aspect ratio when the height is changed.

I can achieve this using the new vh unit: http://jsbin.com/AmAZaDA/3 (resize browser height)

<body>
    <div></div>
</body>

 

html, body {
    height: 100%;
    width: 100%;
    margin: 0;
}

div {
    height: 100%;
    width: 130vh;
    margin: 0 auto;
    background: #f0f;
}

However, I worry about fallback for IE8 and Safari, as it this unit is not supported there.

Are there any other CSS only methods of achieving this effect?

Answer

avrahamcool picture avrahamcool · Oct 3, 2013

I have a solution that works also with IE8 (using Pure CSS 2.1), but not perfectly. because I need the browser to recalculate things when he get resized, and apparently it doesn't do that unless he has to (and I cant find a way to make him think he has to), so you will have to refresh the page after resizing.

as far as I know, the only element that can scale reserving his ratio is an <img>, so we will use the <img> to our advantage.

SO, we are going to use an image with the ratio that we want (using the services of placehold.it), lets say we want a 13X10 ratio (like in your example), so we'll use <img src="http://placehold.it/13x10" />. that image will have a fixed height of 100% the body, and now the width of the image scales with respect to the ratio. so the width of the image is 130% height of the body.

that image is enclosed within a div, and that div has inline-block display, so he takes exactly the size of his content. witch is the size you want.

we remove the image from the display by using visibility: hidden; (not display:none; because we need the image to take the space), and we create another absolute div, that will hold the actual content, that will be right above the image (100% width and 100% height of the common container).

That works perfectly when you first initiate the page, but when you resize the page, the browser doesn't always measure the right width and height again, so you'll need to refresh to make that happened.

Here is the complete HTML:

<div class="Scalable">
    <img class="Scaler" src="http://placehold.it/13x10" />
    <div class="Content"></div>
</div>

and this simple CSS:

html, body, .Content
{
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body
{
    text-align: center;
}

.Scalable
{
    position: relative;
    display: inline-block;
    height: 100%;
}

.Scaler
{
    width: auto;
    height: 100%;
    margin-bottom: -5px;
    visibility: hidden;
}
.Content
{
    position: absolute;
    top: 0;
    background-color: black;
}

Here's a Fiddle (don't forget to refresh after resizing) I recommend you to copy this code to your local machine and try it there rather then within the fiddle.