gpt4 book ai didi

html - 如何使用 CSS 居中和裁剪图像以始终显示为方形?

转载 作者:技术小花猫 更新时间:2023-10-29 11:34:57 24 4
gpt4 key购买 nike

我需要始终仅使用 CSS 将随机大小的图像裁剪为 160x160 的正方形。图片在裁剪时应保持居中。

我的标记应该是:

<a href="#" class="cropper">
<img src="image" alt="description" />
</a>

在 StackOverflow 上搜索我找到了一些答案(例如 CSS - How to crop an image to a square, if it's already square then resize it ),但它们不适用于您的图像水平(宽)垂直(高)更大的情况.

具体来说,我需要能够像这样呈现宽幅图像:

wide image

还有像这样的高大图片:

tall image

正方形,事先不知道哪个是水平矩形或垂直矩形。它还应该支持已经平方的图像。

最佳答案

jsFiddle Demo

div {
width: 250px;
height: 250px;
overflow: hidden;
margin: 10px;
position: relative;
}
img {
position: absolute;
left: -1000%;
right: -1000%;
top: -1000%;
bottom: -1000%;
margin: auto;
min-height: 100%;
min-width: 100%;
}
<div>
<img src="https://i.postimg.cc/TwFrQXrP/plus-2.jpg" />
</div>


关于尺寸的说明

作为Salman A评论中提到,我们需要设置 img 的位置坐标(上、左、下、右),以使用高于图像实际尺寸的百分比。我在上面的例子中使用了1000%,当然你可以根据自己的需要进行调整。

Before and after the fix

* 进一步说明:当我们设置imgleftright(或者:top底部)坐标为-100%(包含div),整体允许的宽度(或: img高度),最多可以是包含div宽度的300% (或:高度),因为它是 div 的宽度(或:高度)和 (或:)坐标。

关于html - 如何使用 CSS 居中和裁剪图像以始终显示为方形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18673900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com