如何中心和裁剪图像与CSS的正方形 [英] how to center and Crop an image to square with CSS
问题描述
我需要总是将一个随机大小的图像裁剪为一个正方形160x160使用CSS。
裁剪时图片应保持居中。
我的标记应为:
< a href =#class =cropper>
< img src =imagealt =description/>
< / a>
在Stackoverflow上搜索我找到了一些答案(例如:
div
{
width:200px;
height:200px;
overflow:hidden;
margin:10px;
position:relative;
}
img {
position:absolute;
margin:auto;
min-height:100%;
min-width:100%;
/ *对于以下设置,我们设置100%,但如果需要可以更高
查看答案的更新* /
left:-100%;
right:-100%;
top:-100%;
bottom:-100%;
}
更新 - h1>
由于评论中提及的
*原因是当我们设置 (或:顶部和底部)坐标为 -100% 的宽度(或 / em>的 div (或: height ),因为它是 div >或 (或:顶部和底部)坐标。
I need to always crop a random-sized image to a square 160x160 using only CSS. The images should stay centered when cropped.
My markup should be:
<a href="#" class="cropper">
<img src="image" alt="description" />
</a>
Searching on Stackoverflow I've found some answers (ex: this) but them doesn't work for horizontal OR vertical images.
I need to be able to transform in a squares both:
and
Without know which one is an horizontal rectangle or a vertical rectangle, it should also support already squared images.
I've no clues and I can't neither write some code to try it, no idea of where start to write it.
Any suggestion?
div
{
width: 200px;
height: 200px;
overflow: hidden;
margin: 10px;
position: relative;
}
img {
position: absolute;
margin: auto;
min-height: 100%;
min-width: 100%;
/* For the following settings we set 100%, but it can be higher if needed
See the answer's update */
left: -100%;
right: -100%;
top: -100%;
bottom: -100%;
}
Update - Improvement
As Salman A mentioned in the comments, the original solution has a flaw - it doesn't work well if the img's height or width (or both) are (at least) 3 times* larger than the containing div.
The problem is shown here.
Salman also gave a really simple and elegant fix. We just need to update the img's position coordinates (top, left, bottom, right) to work with higher percents. The following fix works with 1000%, but of course you can adjust it according to your needs.
The fix is shown here.
* The reason is that when we set the img's left and right (or: top and bottom) coordinates to be -100% (of the containing div), the overall allowed width (or: height) of the img, can be at most 300% of the containing div's width (or: height), because it's the sum of the div's width (or: height) and the left and right (or: top and bottom) coordinates.
这篇关于如何中心和裁剪图像与CSS的正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!