1

I found many examples where to have width 100% and altering the height to have the aspect to be 16:9, but i'd like to have the div to fill the height and the width to be altered, centered.

Example for height: Maintain the aspect ratio of a div with CSS

It will create an aspect 16:9 css only, that would be the best.

Community
  • 1
  • 1
Daniel
  • 795
  • 1
  • 10
  • 25
  • What do you need to put in the div ? What type of content ? – enguerranws Dec 11 '15 at 14:10
  • Possible duplicate of http://stackoverflow.com/questions/1495407/how-to-maintain-the-aspect-ratio-of-a-div-using-only-css – leroydev Dec 11 '15 at 14:17
  • 1
    [This](http://stackoverflow.com/q/33442754/1016716) is a better duplicate, except it doesn't have any answers. – Mr Lister Dec 11 '15 at 14:36
  • @enguerranws The content is varying with single images, text or mixed to make it look like a screen. – Daniel Dec 11 '15 at 14:40
  • As far as I know, this could be done using JS, not CSS. Still looking on it. The thing is : you try to put a 16/9 div that has the height of the window. So if the window ratio is less than 16/9, your div overflow on left and right ? – enguerranws Dec 11 '15 at 14:50
  • @enguerranws Seems like I have to decide that on the outher aspect ratio and eventually lower the height when reaching 100% width. Seems like it will be a job for js. – Daniel Dec 11 '15 at 14:58
  • Right : you could only have height relative to window height and width relative to window width (so you won't be able to get the initial ratio of the window using CSS) as long as you need to set it according to the same reference (width or height). – enguerranws Dec 11 '15 at 15:03

1 Answers1

0

Did it with jquery, here is my solution.

HTML

<div id="aspect" style="margin:auto; width:100%; height:100%;"></div>

JQUERY

function setAspect(aspect) {
    var div = $("#aspect");
    div.css("height","100%").css("width","100%");
    var height = div.outerHeight(false);
    var width = div.outerWidth(false);
    var fullaspect =  width / height;
    if (aspect > fullaspect) {
        //adjust height
        div.css("height", width / aspect);
    } else {
        //adjust width
        div.css("width", height * aspect);
    }
}

setAspect(16/9);
//setAspect(4/3);
//setAspect(1);

Have a nice day.

Daniel
  • 795
  • 1
  • 10
  • 25