如何居中和裁剪图像始终以CSS呈现方形? [英] How to center and crop an image to always appear in square shape with CSS?

查看:136
本文介绍了如何居中和裁剪图像始终以CSS呈现方形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要总是只使用CSS将随机大小的图像裁剪为160x160的正方形。
裁剪后图像应保持居中。



我的标记应该是:

 < a href =#class =cropper> 
< img src =imagealt =description/>
< / a>

在StackOverflow上搜索我找到了一些答案(例如 。

Salman也给了一个非常简单和优雅的修复。我们只需要更新 img 的位置坐标(顶部,左侧,底部,右侧)以使用更高的百分比。以下修补程序适用于 1000%,但当然可以根据您的需要进行调整。



显示修复程序



*原因是当我们设置 left 时> (或: top bottom )坐标为 -100% >包含 div width (或: height ),因为它是 div (或: height )和 left (或: top / em>)坐标。


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 (such as this), but they don't work for cases where your image can be larger horizontal (wide) OR vertical (tall).

Specifically, I need to be able to present both a wide image like this and a tall image like this in square form, without knowing in advance which one is a horizontal rectangle or a vertical rectangle. It should also support already squared images.

解决方案

jsFiddle Demo

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆