Search code examples
csslayoutfluid-layout

Sizing width of an element as a percentage of its height or vice versa in a fluid design?


Im making a responsive design, which has to keep the proportions of its elements (height to width) no matter what the screen size is, so i don't know the size in pixels for any of the elements and i can work only in %.

I can set either the width or the height as a % of the browser size, but the i have no idea how to set the other property value.

That using only CSS, making JS calculate the values is not an option.


Solution

  • I came across this problem last year and found an obscure solution after some tedious researching. Unfortunately it involves wrapper DIVs. The structure is simple - you have a parent DIV which contains the contents container and another DIV that sets the proportions. You set the margin-top of the 'proportion' DIV as percent of the width of the parent... Example:

    #parent {
        position: relative;
    }
    .proportions {
        margin-top: 75%; /* makes parent height to 75% of it's width (4:3)  */
    }
    .container { /* contents container with 100% width and height of #parent */
        position: absolute;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
    }
    

    http://jsfiddle.net/twpTU/