Home > Mobile >  resize image with aspect ratio 4:3 to 16:9 without losing the responsive behaviour with css
resize image with aspect ratio 4:3 to 16:9 without losing the responsive behaviour with css

Time:09-12

Suppose that I have this image (640x480) in 4:3 aspect ratio:

enter image description here

And the code to show it is:

<img src="../static/images/image4-3.jpg" alt="">

What I want is to show it in 16:9 (the real aspect ratio of that image, the dimensions are 640x360):

enter image description here

Is obvious that doing 16/9=1.77777777778 => 640/1.77777777778 = 360. So if set an style for "height: 360px" and "width: 100%" it works, but, it's not responsive, there is a way to edit the height of an image (dinamically) and mantain the responsive behaviour given by bootstrap?

By the way, I'm really new to CSS, so maybe this is an stupid quesiton.

CodePudding user response:

As Bootstrap has buil-in helpers to apply ratio to your elements, you may use those built-in helpers that will allow you to have the ratio you want along with keeping things responsive. To do so:

  1. wrap your image in a div
  2. apply ratio ratio-16x9 classes to that div. Those classes will make that div a responsive 16/9 container.
  3. apply img-fluid to the image so that it scales nicely with its container.

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<!-- note the "ratio ratio-16x9" classes on the parent div -->

<!-- resize the screen to see how the image nicely scales while maintaining the desired ratio -->

<!-- for demo purpose, am setting the width of the wrapper div to 75% so that the ratio effect can be easily seen -->
<div >
  <img src="https://i.stack.imgur.com/p4xRM.jpg" >
</div>

Learn more about Bootsrap 5 Ratio Helpers on BS5 docs.

It is worth noting that there is a native way to apply ratios using aspect-ratio rule but that later rule still (at the time of writing) doesn't have a good browser support.

  • Related