简体   繁体   English

我们如何使用 TailwindCSS 按比例缩放图像以始终适合视口?

[英]How can we use TailwindCSS to proportionally scale an image to always fit within the viewport?

We would like to use TailwindCSS to proportionally scale an image (ie without altering the aspect ratio) such that the image is fully visible "above the fold", horizontally and vertically centered, and has a configurable amount of padding between the image and sides of the window.我们想使用 TailwindCSS 按比例缩放图像(即不改变纵横比),使图像在“折叠上方”完全可见,水平和垂直居中,并且在图像和两侧之间具有可配置的填充量window。

For example, say we have some code which looks like this ( Tailwind Playground ):例如,假设我们有一些代码如下所示 ( Tailwind Playground ):

 <link rel="stylesheet" href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css" /> <html lang="en" class="min-h-screen bg-gray-50"> <body class="min-h-screen"> <div class="flex flex-col items-center justify-center"> <div class="flex min-h-screen sm:px-12 py-8"> <img class="h-auto max-w-full drop-shadow-md sm:rounded-md" src="https://via.placeholder.com/1500x2500" alt="" /> </div> </div> </body> </html>

Here the image needs to be resized such that its height is not larger than the available screen.这里需要调整图像的大小,使其高度不大于可用屏幕。 Additionally there should be padding between the image and sides of the screen.此外,图像和屏幕两侧之间应该有填充。 (The sm breakpoint can be ignored; this is more important for larger screens.) (可以忽略sm断点;这对于较大的屏幕更为重要。)

Ideally this will be achieved using only CSS (Tailwind specifically), however if necessary JavaScript is an option.理想情况下,这将仅使用 CSS(特别是 Tailwind)来实现,但如果需要,也可以选择 JavaScript。

Use .h-screen on the parent to your img .在父级上使用.h-screen到您的img Then on your image use .object-scale-down with max-h-full and m-auto .然后在您的图像上使用.object-scale-downmax-h-fullm-auto

Tailwind Play .顺风播放

 <link rel="stylesheet" href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css" /> <html lang="en" class="bg-gray-50"> <body> <div class="flex justify-center sm:px-12 p-8 h-screen"> <img class="object-scale-down max-h-full drop-shadow-md rounded-md m-auto" src="https://via.placeholder.com/1500x2500" alt="" /> </div> </body> </html>

I hope this will this is what you are looking for.我希望这就是您要找的。

 <link rel="stylesheet" href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css" /> <html lang="en" class="min-h-screen bg-gray-50"> <body class="min-h-screen"> <div class="flex flex-col items-center justify-center"> <div class="flex min-h-screen h-screen"> <img class="h-auto object-contain max-w-full drop-shadow-md rounded-md" src="https://via.placeholder.com/1500x2500" alt="" /> </div> </div> </body> </html>

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

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