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?
CSS calc() is a function used for simple calculations to determine CSS property values right in CSS. The calc() function allows mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values.
In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.
object-fit: cover; width: 100%; height: 250px; You can adjust the width and height to fit your needs, and the object-fit property will do the cropping for you.
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%;
}
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With