【问题标题】:How to vertically center a image in a div?如何在div中垂直居中图像?
【发布时间】:2015-08-06 16:35:58
【问题描述】:

我在 div 中有以下图片

  <div id="left-control">
      <img src="img/icons/ic_next_3x_re.png" />
   </div>

这是css

#left-control {
   height: 100%;
   float: left;
}

#left-control > img {
    display: block;
    margin: 250px 0;
    z-index: 1;
}

但由于某种原因,无论我尝试什么 CSS,我似乎都无法将图像垂直居中。有什么建议吗?

【问题讨论】:

标签: html css


【解决方案1】:

没有什么神奇的方法可以做到这一点,但下面的内容应该可以解决问题。

#left-control {
   float: left;
   height: 100%;
}

#left-control:before {
    content: "";
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

#left-control img {
    vertical-align: middle;
    z-index: 1;
}

这是simple fiddle。请记住,我在此示例中手动设置了 #left-control 元素的高度,因为 fiddle 不允许 100%。

【讨论】:

  • 嘿,有没有办法水平居中? margin: 0 auto; 似乎不起作用。 fiddle here
  • @Solace 移除浮动:左;并添加 text-align: center;
【解决方案2】:

您可以使用 CSS 表格来完成此操作。

.wrapper {
   display: table;
  height: 300px;
  border: 1px solid black;
}
#left-control {
  height: 100%;
  display: table-cell;
  vertical-align: middle;
}

#left-control > .img {
  display: inline-block;
  width: 100px;
  height: 100px;
  z-index: 1;
  background: red;
}
<div class="wrapper">
  <div id="left-control">
    <div class="img"></div>
  </div>
</div>

【讨论】:

    【解决方案3】:

    你可以像这样将 img 包装在另一个 div 中。

    <div id="left-control">
          <div class="vert-align">
             <img src="img/icons/ic_next_3x_re.png" />
          </div>
       </div>
    

    然后,在 css 中做这样的事情......

    #left-control {
       height: 100%;
       position:relative;
    }
    
    #left-control > img {
        display: block;
        margin: 250px 0;
        z-index: 1;
    }
    
    .vert-align{
        position: absolute:
        margin: auto:
        top:0; left:0; right:0; bottom:0;
        height: 100px;
    }
    

    您可以使用左上角和右下角属性将其设置到所需的位置。

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 2012-02-27
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 2011-04-08
      相关资源
      最近更新 更多