Suppose that I have this image (640x480) in 4:3 aspect ratio:
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):
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:
- wrap your image in a
div
- apply
ratio ratio-16x9
classes to thatdiv
. Those classes will make thatdiv
a responsive16/9
container. - 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
onBS5
docs.
It is worth noting that there is a native way to apply
ratio
s usingaspect-ratio
rule but that later rule still (at the time of writing) doesn't have a good browser support.