Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a calc() to create an auto-sized element according to aspect ratio?

Tags:

css

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?

like image 265
RandallB Avatar asked May 11 '13 08:05

RandallB


People also ask

How does the CALC () function work on values in CSS?

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.

How do I create aspect ratio in CSS?

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.

How do I change the aspect ratio of an image in CSS?

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.


3 Answers

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%;
}
like image 158
jono Avatar answered Oct 31 '22 16:10

jono


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.

like image 44
MaxPRafferty Avatar answered Oct 31 '22 16:10

MaxPRafferty


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);
}
like image 40
pzin Avatar answered Oct 31 '22 18:10

pzin