9

I have a video container, and it'd be splendid if I could use calc to calculate the height based on the width.

There are some inklings of stackoverflow answers that claim something like this is possible:

.selector{
  width: 100%;
  height: calc(width * 1.75);
}

But I haven't seen that work in Chrome 26. How can I calculate the height only using CSS3?

Community
  • 1
  • 1
RandallB
  • 5,415
  • 6
  • 34
  • 47
  • How about using `aspect-ratio: 1 / 1.75;` - See here: https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio – Chris Barr Aug 16 '23 at 11:49

6 Answers6

7

There is a way to get around this that bypasses the need to use calc() that I thought I ought to make you aware of.

You can set the height to zero and use padding as it is relative to the elements width to create a fixed ratio.

.selector {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom:175%;
}

I often use this technique to display 16:9 YouTube videos responsively. To do this all you have to do is set the child element like this -

.selector .child {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
}
jono
  • 1,792
  • 17
  • 18
5

Using vh and vw units is a nice method for getting a fixed responsive viewframe:

.sixteen-nine {
   width: calc(75vh * 1.77);
   height: 75vh;
}

That will give you a viewport relative to screen height at approximately 16:9.

MaxPRafferty
  • 4,819
  • 4
  • 32
  • 39
1

For the moment the CSS variables aren't really supported yet. I think they work in WebKit.

If you need that to be a variable, you should use for the moment some CSS preprocessor such as Sass, less or Stylus.

But I am not sure if you really need the width to be a variable. In any case, in plain CSS you need that to be a real value for the moment:

div {
  height: calc(100% * 1.75);
}

In the future, we could do something like this:

div {
  var-height: 100%
  height: calc(var(height) * 1.75);
}
pzin
  • 4,200
  • 2
  • 28
  • 49
1

Since 2021 all modern browsers support the aspect-ratio CSS property. So that's another option.

Roman Starkov
  • 59,298
  • 38
  • 251
  • 324
0

Since videos are (usually) 16/9 you can
use a simple calc solution while keeping
your video or iframe responsive.

iframe {width: 100%; height: calc(~'100% * 9/16');}
Sagive
  • 1,699
  • 1
  • 24
  • 34
0

Using the padding trick and some CSS variables:

div{
 --w: 50%;
 --ratio: 2; /* width / height */
 
  width: var(--w);
  padding-top: calc(var(--w)/var(--ratio));
  
  background: #EEE;
  outline: 1px solid #CCC;
  position: relative;
}

/* Demo content, could be anything */
div::before{
  content: "VIDEO";
  font: 700 4vw Arial;
  color: #AAA;
  display: grid;
  place-items: center;

  /* important part: */
  position: absolute;
  top:0; right:0; bottom:0; left:0;
}
<div></div>
vsync
  • 118,978
  • 58
  • 307
  • 400