Search code examples
csshtmlheightwidth

Resize div width relative to its height to keep aspect ratio


I want to keep the .center div's width relative to its height by 4:3 aspect ratio (4 width per 3 height) and height of 100%; Then align center the div horizontally.

Like you can see here with a flash application.

This is what I have:

HTML:

<div id="stuff" class="center" width="800" height="600"> 
     <canvas id="someHTML5">You cant play HTML5</canvas>
</div>

CSS:

.center {
    position: absolute;
    left: 50%;
    width: 800px; /* how do I make this relative; i want: pseudo code: width: height/3*4; */
    height: 100%;
    margin-left: -400px; /* -width/2 for horizontal alignment */
    z-index: 100;  
}

I have also a JavaScript loop to integrate JavaScript side updates.


Solution

  • Since the width of the box should be changed relative to its height, you could use vh viewport relative length as the value of the width property.

    From the Spec:

    The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

    vh unit
    Equal to 1% of the height of the initial containing block.

    Here you go:

    .center {
        position: absolute;
        left: 50%;
        width: 133.33vh; /* 100 * 4/3 ratio */
        height: 100%;
        margin-left: -66.66vh; /* width / 2 */
        z-index: 100;
    }
    

    WORKING DEMO.

    It's worth noting that vh, vw viewport-percentage lengths are supported in IE9+.


    Browser compatibility

    enter image description here

    Credits: Mozilla Developer Network