16:9 aspect ratio with fixed width
Asked Answered
J

5

10

If I were to embed a YouTube video for example

<iframe width="560" src="http://www.youtube.com/embed/25LBTSUEU0A" class="player" frameborder="0" allowfullscreen></iframe>

Using jQuery would I set a height with an aspect ration of 16:9 so if the width is 560 the height should be 315px.
I have this jquery to set a height but I dont know how to apply the 16:9 ratio

$('.player').parent().attr('width', ':9ratio');

or can this be done neatly using css?

Jonniejonny answered 4/11, 2011 at 19:2 Comment(1)
possible duplicate of Get YouTube Video dimensions (width/height)Jaimeejaimes
S
24

Aspect ratio is just width:height. So if you wanted to calculate the height based on a known width it is pretty straightforward.

//width=560, wanted height is 315
$('.player').parent().attr('height', 560*9/16);
Shippen answered 4/11, 2011 at 19:6 Comment(2)
For bonus points, whats the opposite? For example, when you have the height, but want the width?Hetman
Flip the divisors, eg 315 * 16/9 = 560Convocation
T
5

I would recommend using css calc instead of jQuery for this:

width: 560px;
height: calc(560px * 9/16);
Titanism answered 21/12, 2015 at 16:5 Comment(1)
this is actually a really good solution for now. I asked this in 2011 and i always though why we can't do this via css. brilliant solution now.Jonniejonny
S
1

Pretty old question but if somebody still seeking for the answer, this one could be a better approach.


    function getRelativeWidth(ratio, crntHght) {
        ratio = ratio.split(":");
        var wdthRto = ratio[0];
        var hghtRto = ratio[1];
        return ((wdthRto*crntHght) / hghtRto); 
    }

    function getRelativeHeight(ratio, crntWdth) {
        ratio = ratio.split(":");
        var wdthRto = ratio[0];
        var hghtRto = ratio[1];
        return ((crntWdth*hghtRto) / wdthRto); 
    }
    var wdth = 1600;
    var hght = 900;
    var getHeight = getRelativeHeight("16:9", wdth); 
    var getWeight = getRelativeWidth("16:9", hght); 

    console.log(getHeight);
    console.log(getWeight);

Superfecundation answered 31/7, 2017 at 11:12 Comment(0)
D
0
$('.player').parent().attr('width', 560*9/16)
Diffusive answered 4/11, 2011 at 19:4 Comment(2)
Does that maintain the aspect ratio?Jury
Do you want it to maintain the aspect ratio if the iframe was to change size?Diffusive
S
-1

The best way is to simply use CSS because u can keep
it responsive as the page loads and not have a visible
'jump' in the iframe width and height.

Also, you don't have to set a fixed width (although u can)

like this:

iframe {width: 100%; height: calc(~'100% * 9/16');}
Savior answered 22/4, 2020 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.