【问题标题】:How to center an img inside a div如何在 div 中居中 img
【发布时间】:2012-08-07 23:50:47
【问题描述】:

我正在尝试一些应该很容易的东西,但我不知道怎么做。

我有这样的 html 源代码:

<div class="product">
  <img src="product123.png" />
</div>`

还有一些 CSS:

.product {
    width: 460px;
    height: 460px;
}

.product img {
      margin: auto;
      display: block;
}

我的图像水平对齐但不是垂直对齐。我尝试了一些position: relative; / bottom: 0; 功能,但它并没有改变任何东西......

有什么想法吗?

感谢您的帮助!

PS:我找到了这个解决方案center <IMG/> inside a <DIV> with CSS,但我宁愿保持这样的 HTML,而且无法以“我的”方式做到这一点似乎令人难以置信。

【问题讨论】:

标签: html css margin


【解决方案1】:

试试这个 - http://jsfiddle.net/tG9UK/

.product {
    width: 460px;
    height: 460px;

    display: table-cell;
    vertical-align: middle;
}

【讨论】:

    【解决方案2】:

    如果你想垂直和水平居中,你应该能够应用 display: table-cell 到 div 并使用 vertical-align

    .product {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        width: 460px;
        height: 460px;
    }
    .product img {
        margin: auto;
        display: block;
    }
    

    【讨论】:

      【解决方案3】:
      .product {
          width: 460px;
          height: 460px;
          line-height:460px;
          text-align:center;
      }
      

      http://jsfiddle.net/EHTeL/1/

      【讨论】:

        【解决方案4】:

        如果图像尺寸是静态的,那么这样的东西对你有用

        .product img {
           position: absolute;
           top: 50%;
           left: 50%;
           width: 300px;
           height: 300px;
           margin-top: -150px; /* Half the height */
           margin-left: -150px; /* Half the width */
        }
        

        【讨论】:

        • 抱歉,我应该明确指出我的图像尺寸不是静态的。
        猜你喜欢
        • 2013-10-04
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        • 2011-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多