【问题标题】:CSS center any image in divCSS使div中的任何图像居中
【发布时间】:2016-09-25 22:02:12
【问题描述】:

假设我有 divwidth: 300pxheight: 200px
我希望div 中的任何图像都水平和垂直居中,无论图像大于还是小于div

对于较小的图像margin: 0 auto 效果很好,但较高的图像会向右突出并且不居中。

对于更大的图像,这可行:

height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

我找不到这些的任何组合,也没有找到任何解决方案如何完美地居中此图像。

【问题讨论】:

标签: html css image center


【解决方案1】:

position: absolute 添加到imgposition: relativediv

.el {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 50px 150px;
}
img {
  opacity: 0.4;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: absolute;
}
<div class="el">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/50x50/000000/ffffff">
</div>

【讨论】:

    【解决方案2】:

    试试这个

    div{
      display: flex;
      align-items: center;
      justify-content: center
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2013-10-30
    • 2013-01-01
    • 2011-04-08
    • 2014-06-02
    相关资源
    最近更新 更多