给定任意图像,我想从图像中心裁剪一个正方形并将其显示在给定的正方形内。
一种解决方案是使用以元素大小为裁剪尺寸的元素为中心的背景图像。
基本例子
.center-cropped { width: 100px; height: 100px; background-position: center center; background-repeat: no-repeat; } <div class="center-cropped" style="background-image: url('http://placehold.it/200x200');"> </div>
img标签示例
img
此版本保留了img标签,因此我们不会丢失拖动或右键单击以保存图像的功能。信贷帕克贝内特不透明度伎俩。
.center-cropped { width: 100px; height: 100px; background-position: center center; background-repeat: no-repeat; overflow: hidden; } /* Set the image to fill its parent and make transparent */ .center-cropped img { min-height: 100%; min-width: 100%; /* IE 8 */ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* IE 5-7 */ filter: alpha(opacity=0); /* modern browsers */ opacity: 0; } <div class="center-cropped" style="background-image: url('http://placehold.it/200x200');"> <img src="http://placehold.it/200x200" /> </div>
object-fit/-position
object-fit
-position
请参阅支持的浏览器 。
的CSS3图像规范定义object-fit和object-position属性,它们一起允许对规模更大的控制和一个的图像内容的位置img元素。有了这些,就有可能达到预期的效果:
object-position
.center-cropped { object-fit: none; /* Do not scale the image */ object-position: center; /* Center the image within the element */ height: 100px; width: 100px; } <img class="center-cropped" src="http://placehold.it/200x200" />