Css object-fit 让img标签像背景图那样填充盒子

有时候我们会希望一张长方形的图片完美填充一个正方形的盒子(不拉伸,图片在盒子里面水平垂直居中)。

css的背景background-sizecover可以使背景图完美填充盒子不使图片失真。

如果不想使用使用背景图来解决这个问题可以使用css3的object-fitcover来解决。

.box {
      /* 父盒子必须固定宽高 */
      height: 200px;
      width: 200px;
      border: 1px solid red;
}
.box img {
      object-fit: cover; /* background-size */
      object-position: center; /* 类似background-position */
      /* 图片必须width和height为100% */
      width: 100%;
      height: 100%;
}
<div class="box">
	<img src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=151472226,3497652000&fm=26&gp=0.jpg" alt="">
</div>
posted @ 2020-07-31 17:15  demo_you  阅读(356)  评论(0编辑  收藏  举报