简体   繁体   中英

How to maintain image aspect ratio and make sure it fits inside the container?

I have been struggling with this problem for a couple of weeks now. I have a container which is 90vh. I have some header text and below it is an image. I need to maintain the aspect ratio of 16:9. But, the height must never exceed the height of the container causing scrollbar to appear. Is it doable??

Here is the calculation for 16:9 aspect ratio

To get height base on width (9 * WIDTH) / 16;

To get width base on height (16 * HEIGHT) / 9

https://codesandbox.io/s/sleepy-sara-ew3oj9?file=/src/styles.css

the .wrapper element never exceed the height of the container, because 90vh isn't working.

❌ the part which is wrong

height: "90vh"; /* turn this from string to number, without this "" */

✅ make it like this:

height: 90vh;

also for the aspect-ratio problem,

you can a native css solution, called aspect-ratio

img {
  aspect-ratio: 16/9;
  width: 100%;
}

with this solution, the image will be always 100%,
but the height change depends on aspect-ratio

 .App { font-family: sans-serif; } * { padding: 0; margin: 0; box-sizing: border-box; } .container { padding: 1rem; margin: 1rem; } .content { display: grid; grid-template-columns: 80% 20%; margin-top: 2rem; gap: 1rem; } .wrapper { height: 90vh; /* turn this from string to number, without this "" */ border: 1px solid; margin: 1rem; } .sidebar { border: 1px solid; } .content img { aspect-ratio: 16/9; width: 100%; }
 <div class="App"> <div class="wrapper"> <div class="container"> <div class="header"> <h1>Here is header</h1> <p>Here is sub header</p> </div> <div class="content"> <img alt="Hello" src="https://images.unsplash.com/photo-1611771341253-dadb347165a8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OHx8YmVhdXRpZnVsJTIwbmF0dXJlfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60" /> <div class="sidebar">Side bar</div> </div> <!-- content --> </div> <!-- container --> </div> <!-- wrapper --> </div> <!-- app -->

Set max-width on your image, to force it to take the size of the grid you defined. Also set a height 100% on your .container class

 img {
      max-width: 100%;
      max-height: 100%;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM