Jon Sud
Jon Sud

Reputation: 11641

How to have aspect ratio by parent height?

I want to have aspect ratio controlled by parent height.

Every example I search in stackoverflow and codepen are examples of aspect-ratio by width size.

In my example I have two div. there height is controlled by wrap div. so in the first div there is a div inside that should display in 16:9 aspect-ratio.

This is mean if the height is 200px then the width should be 355px (200*(16/9)).

Please keep in mind that height can change because I use vh.

How to do that with css?

Here is my example code in codepen

.wrap { display:grid;grid-template-columns:1fr;grid-template-rows:30vh 70vh; }

.item { border:1px solid red; }

.aspect-ratio { background:blue; height: 100%; }
<div class="wrap">
 <div class="item">
   
   <div class="aspect-ratio">aspect ratio should be 16:9</div>
   
  </div>
 <div class="item"></div>
</div>

Upvotes: 1

Views: 415

Answers (1)

Alireza Sabahi
Alireza Sabahi

Reputation: 675

you can use css calc();

.wrap { display:grid;grid-template-columns:1fr;grid-template-rows:30vh 70vh; }

.item { border:1px solid red; }

.aspect-ratio { background:blue; height: 100%; width: calc(30vh * 16 / 9); }
<div class="wrap">
 <div class="item">
   
   <div class="aspect-ratio">aspect ratio should be 16:9</div>
   
  </div>
 <div class="item"></div>
</div>

Upvotes: 1

Related Questions