Question

I have set up a <div> that resizes, depending on the width of the browser window. How can I make the height automatically set to match the width in proportion? In other words, I need the height to be 50% of the width, for example. I need it to work without JavaScript.

Was it helpful?

Solution

Here's one hack that you can use: a quirk with CSS is that the top and bottom paddings/margins, when set to percentages, are computed based on the width of the parent element, not its height.

So, if you want a square div, which is, say, 50% the width of its parent element. To make it square, you simply set it's bottom padding to 50%, too.

The thing is that you have to adjust the padding percentage based on the div's width. If the div's width is set to 75% of parent, for example, to get a square you will need to use a bottom padding of 75%.

div {
    background-color: #eee;
    width: 50%;
    height: 0;
    margin-bottom: 40px;
}
.square {
    padding-bottom: 50%; /* (50%*1) */
}
.landscape {
    padding-bottom: 37.5%; /* (50%*(3/4)) */
}
.portrait {
    padding-bottom: 66.6667%; /* (50%*(4/3)) */
}

Here's a proof-of-concept fiddle: http://jsfiddle.net/teddyrised/Vsj33/

OTHER TIPS

If you know the ratio of your image, then you might be abble to keep the same ratio for your div.

DEMO (rezise window's width)

How does this work ?

  1. Insert a floatting pseudo element inside the box
  2. set it a vertical padding in percentage value. This % will take the box width as reference.

So a padding vertical of 100%, will stretch the box to a square. It will grow longer if content inside has not enough room :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top