[英]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:如果
height
和width
都是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:如果
height
和width
都是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.