简体   繁体   English

保持 div 内图像的纵横比

[英]Maintain aspect ratio of an image within a div

I'm trying to make my own lightbox and something that I can not get over is parent fitting to image, maintaining its ratio.我正在尝试制作自己的灯箱,而我无法克服的事情是父母适合图像,保持其比例。 The lightbox idea is that it's supposed to display any image (portrait, landscape) correctly, so this is not a 'wrong image' case.灯箱的想法是它应该正确显示任何图像(肖像、风景),所以这不是“错误图像”的情况。

The case: My parent div fits the portrait-oriented picture's original width while keeping a nice max-height of 90vh.案例:我的父 div 适合纵向图片的原始宽度,同时保持 90vh 的最大高度。 Which results in disorting the picture's ratio.这导致图片的比例失真。

The project: https://bambi007.github.io/veneer-in-shambles/项目: https://bambi007.github.io/veneer-in-shambles/

The code:编码:

 #veneer { position: fixed; width: 100vw; height: 100vh; background: #0000008e; z-index: 10000; display: none; align-items: center; justify-content: center; &.veneer-on { display: flex; }.veneer-image-container { position: relative; max-height: 90vh; max-width: 90vw; display: flex; border: 10px solid tomato; .veneer-image { border: 10px solid white; max-width: 100%; max-height: 100%; // object-fit: contain; } } }
 <div id="veneer"> <div class="veneer-image-container"> <div id="veneer-close-button" title="close"></div> <img class="veneer-image" src="" alt=""> </div> </div>

I have come up with an algorithm that calculates best width of image container to display the image maintaining its ratio.我提出了一种算法,可以计算图像容器的最佳宽度以显示图像并保持其比例。 Probably I will improve it in near future.可能我会在不久的将来改进它。

 if (veneerImage.naturalHeight > veneerImageContainer.offsetHeight) { var heightDifference = veneerImage.naturalHeight - veneerImageContainer.offsetHeight var percentage = heightDifference / veneerImage.naturalHeight * 100 var containerWidth = veneerImage.naturalWidth - (veneerImage.naturalWidth / 100 * percentage) veneerImageContainer.style.width = containerWidth + 'px'; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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