2

is it possible to have a div (or other element) resize its height in relation to its width (or the other way around) using CSS? basically, to get it to behave the way an image with a percentage width resizes proportionally as the browser window is resized?

jFrymann
  • 45
  • 1
  • 7
  • You can try using ems as a unit of measure. If you combine it with Oscar's solution below, you can define/adjust the parent's dimensions in pixels and get proportional results. – 2C-B Mar 14 '14 at 18:30

2 Answers2

3

If you want to set a width or height relative to a .parent element and you know the aspect ratio that needs to be maintained, you can do something like this:

.parent{
    width: 150px;
}
.child{
    width: 100%;
    padding-top: 50%; /* outer height will be 75px (150px*0.5) */
}

Note that you are relying on having a height (or width) of 0 and defining it based on the padding only. So, if you want to add any content you will probably need to wrap it within an absolutely positioned div within .child. See this fiddle for an example

Oscar
  • 915
  • 10
  • 15
0

Look at this related question. In short: No, it's not possible using only CSS

Community
  • 1
  • 1
Wesley
  • 2,204
  • 15
  • 14
  • thanks @Wesley, that makes sense, a cross browser IE expression type solution would have been ideal but is not possible. I'm still wondering about the way the browser resizes images (and embed, object, video tags). what is special in those cases and is it possible to have a div emulate that same behavior? – jFrymann Jan 19 '12 at 19:22
  • divs arent images indeed, and browsers treat them different. You can emulate the behaviour, but not in CSS. Using javascript it's not that difficult. – Wesley Jan 20 '12 at 08:32