【问题标题】:CSS to center img horizontally and vertically without resizingCSS将img水平和垂直居中而不调整大小
【发布时间】:2018-07-04 18:18:49
【问题描述】:

我有这样的代码:

<div class='image-holder' style='width:128px; height:128px'>
    <img class='thumbnail' src='image1.png'>
</div>

.thumbnail 的实际大小未知,可能不是精确的正方形。

所以我想要做的不是改变图像(.thumbnail)的尺寸,而是只显示 .image-holder 元素内图像的中心(水平和垂直)。

例如,如果图像 (.thumbnail) 为 256x256,则图像的内部 128x128 部分应显示在 .image-holder 内。

我愿意使用实际的 img 元素,或者为 div 使用 background-image。我都试过了,都没有成功。

如果有必要,我相当肯定我可以编写一些 javascript 来完成这项工作,但在我走这条路之前,我想看看是否有纯 CSS 解决方案。

【问题讨论】:

  • 对象拟合:封面;想到了css。

标签: html css image


【解决方案1】:

您应该为此使用background-image。只需从中删除默认重复,然后设置background-position: center;

看这里:

.image-holder {
  width:128px;
  height:128px;
  border: 1px solid red;
  margin: 10px;
  background-repeat: no-repeat;
  background-position: center;
}

#holder-1 {
  background-image: url('http://via.placeholder.com/350x150');
}

#holder-2 {
  background-image: url('http://via.placeholder.com/100x100');
}
<div id="holder-1" class='image-holder'></div>
<div id="holder-2" class='image-holder'></div>

【讨论】:

  • 谢谢。非常适合我的场景。
猜你喜欢
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多