1

I'm using the technique from this answer to create a DIV that maintains its aspect ratio when the browser viewport is resized.

However, I want the DIV to only get so big and then stop. But, if I apply max-width: 300px; to the containing div, the div will stop expanding its width when the viewport gets big enough, but the height keeps going, losing the aspect ratio. If I apply max-height: 60px;, it has no effect whatsoever.

How do I get a div to expand with the width of a viewport, maintain its aspect ratio, and stop expanding both height and width at a specified maximum width?

Live code here.

body {
    width: 36%;
    margin: 8px auto;
}

div.stretchy-wrapper {
    width: 100%;
    padding-bottom: 56.25%; /* 16:9 */
    position: relative;
    max-width: 300px;
    background: blue;
}

div.stretchy-wrapper > div {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;

    color: white;
    font-size: 24px;
    text-align: center;
}
Community
  • 1
  • 1
Questioner
  • 7,133
  • 16
  • 61
  • 94
  • Is this a dublicate http://stackoverflow.com/questions/1495407/css-a-way-to-maintain-aspect-ratio-when-resizing-a-div ? – Persijn Apr 09 '15 at 07:31
  • @Persijn, no, because I already reference an answer on that exact question and outline specifically what further features I am looking for. – Questioner Apr 09 '15 at 07:39

2 Answers2

0

It looks like the issue is because of the padding which increases the height by % based on resize

below is the example in which i have added box-sizing:border-box; and gave height which on resize remains the same

http://dabblet.com/gist/85df841bd1602d24829f

Vitorino fernandes
  • 15,794
  • 3
  • 20
  • 39
  • Thank you for responding. Sorry if my question was unclear, but it seems in the code you provided, the red box scales both in width and height at different viewports. If I go very thin, the red box gets thin but stays tall. If I go wide, the red box expands vertically. I'm not totally sure what is going on, but it's not what I was hoping for. I was looking for something that would keep the same aspect ratio no matter what, and stop expanding at a certain size. – Questioner Apr 09 '15 at 07:33
0

One possible solution seems to be to simply create a containing div around the wrapper div, and apply max-width to that.

Questioner
  • 7,133
  • 16
  • 61
  • 94