Resize div to largest possible size when constrained by size of parent div and a aspect-ratio [duplicate]

StackOverflow https://stackoverflow.com/questions/19500080

Domanda

Background:

I have the html:

<div id="container">
  <div id="page"></div>
</div>

Where #container is a fluid element that's width and height is determined by the window size.

Question:

What I am trying to do is programtically set the height and width of #page so it occupys the largest size it can while being constrained by:

  • It must not be larger than #container
  • It must maintain a given aspect ratio e.g. 16:9

The part I am struggling with most its making it fill the largest size it can relative to the parent div.

Any help would be much appreciated.

Thanks

È stato utile?

Soluzione

I'm not sure on my actual syntax, but the idea should work just fine.

var container = document.getElementById('container');
var page = document.getElementById('page');

var scale = Math.min(container.width / 16, container.height / 9)

page.width(scale * 16);
page.height(scale * 9);

Altri suggerimenti

You could also achieve the desired effect without the use of Javascript by setting the aspect ratio in the containing elements padding-top: 56.25%;. The page element will need to be anchored, for example top: 0; right: 0; and set you width/height to 100%. Here is an updated JSFiddle for your review: CLICK HERE

HTML:

<div id="container">
    <div id="page"></div>
</div>

CSS:

#container{
    position: relative;
    padding-top: 56.25%;   /*16:9 aspect ratio*/
    background:#ff0;
}
#page{
    position: absolute;
    width:100%;
    height: 100%;
    top: 0;
    right: 0;
    background:red;
    opacity: 0.5;
}

use this JQuery code:

jsFiddle

var parentw = $("#page").parent().width();
$("#page").height(function(){
    return parentw*9/16;
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top