简体   繁体   English

缩放图像以适应屏幕而不改变其纵横比

[英]Scale an image to fit the screen without changing its aspect ratio

How can I have an image take scale the screen while keeping it's aspect ratio in CSS?如何让图像缩放屏幕,同时保持 CSS 的纵横比? For example, if I have an image that is taller than it is wide its height should be 100% (and width: auto; ).例如,如果我有一个比宽度高的图像,它的height应该是100% (和width: auto; )。 But if the image is wider than it is tall its width should be 100% (and height: auto; ).但是,如果图像宽于高,则其width应为100% (和height: auto; )。

Can I do this in CSS?我可以在 CSS 中执行此操作吗?

If the height and the width are both 100% than the image is all squished together like so:如果heightwidth都是100% ,那么图像就会像这样被挤压在一起:

在此处输入图像描述

If the height and width are both auto , the image scales correctly unless it is smaller than the screen's size, then it leaves gaps around its edges:如果heightwidth都是auto ,图像会正确缩放,除非它小于屏幕的尺寸,然后它会在边缘留下间隙:

在此处输入图像描述

You can use object-fit: cover , this ensures that the image doesn't lose its aspect ratio.您可以使用object-fit: cover ,这可以确保图像不会丢失其纵横比。 You can also use a percentage value like width: 70% , and height: auto so the image scales down when resized您还可以使用像width: 70%height: auto这样的百分比值,这样图像在调整大小时会缩小

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

相关问题 如何在不剪切或干扰其纵横比的情况下将图像放入 div? - How to fit a image into a div without cutting or disturbing its aspect ratio? 缩放没有宽高比的SVG图像 - Scale SVG image without aspect ratio 更改图像的纵横比而不进行裁剪 - Changing aspect ratio of a image without cropping 更换浏览器时具有适合背景的屏幕并保持宽高比 - Having background fit screen and maintain aspect ratio when changing browsers 如何在不改变宽高比的情况下强制图像和视频适合div? - How to force the image and video to fit inside the div without changing aspect ratio? 如何在保持纵横比的同时缩放背景图像以适应屏幕的整个宽度? 当我使用“封面”时,高度被切断 - How to scale a background image to fit the full width of the screen while maintaining aspect ratio? Height is cut off when I use "cover" 使 canvas 大小适合背景图像大小,保持其纵横比 - Fit canvas size to background image size, keeping its aspect ratio 如何使用CSS拉伸图像以适应屏幕并保持纵横比? - How to stretch an image to fit screen and maintain aspect ratio using CSS? 在不损失宽高比的情况下将图像适合特定尺寸的盒子? - Fit image into specifically sized box without losing aspect ratio? 缩放一个 div 以适应 window 但保持纵横比 - Scale a div to fit in window but preserve aspect ratio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM