【问题标题】:Vertically and horizontally align an image in a div垂直和水平对齐 div 中的图像
【发布时间】:2014-02-21 02:48:34
【问题描述】:

我需要一个相对于 div 顶部和 div 侧面居中的图像。换句话说,div的左边缘和图像的左边缘之间的空间量必须与对面的空间量相同。 div 的上边缘和图像的上边缘也是如此。我从this 问题中查看了以下代码并得到了这个(除了类是 id 之外几乎相同)。

CSS:

#img_holder {
    background-color:#EC0610;
    height: 500px;
    float:left;
    width: 550px;
    text-align: center;
}

#vertical_center {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}    

#image {
    vertical-align: middle;
    max-height: 500px;
    max-width: 550px;
}

HTML:

<div id="img_container">

  <div id="left_ctrl">

      Left control buttons

  </div>

  <div id="img_holder">

      <div id="vertical_center">

           <!-- Image inserted by javascript but the resulting html is this --> 
           <img id="image" src="../../images/bball1.jpg />

      </div>

  </div>

  <div id="right_ctrl">

      Right control buttons

  </div>

</div>

我的图像水平居中显示,但不是垂直居中。关于为什么的任何想法?浏览器是在 Arch Linux 上运行的 Chromium 32。

【问题讨论】:

  • 也发布您的 HTML。

标签: css image html centering


【解决方案1】:

HTML:

<div id="img_holder">
    <img id="image" src="http://placehold.it/300x300">
</div>

CSS:

#img_holder {
    background-color:#EC0610;
    height: 500px;
    width: 550px;
    position: relative;
}

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

演示:JSFIDDLE

【讨论】:

    【解决方案2】:

    好吧,考虑到this approach,您在标记中犯了一个错误。图像不应嵌套在 #vertical_center 元素中。换句话说,#image#vertical_center 元素应该是siblings,如下所示:

    <div id="img_holder">
        <div id="vertical_center"></div>
        <img id="image" src="http://placehold.it/200" />        
    </div>
    

    UPDATED DEMO.

    另外,两个inline-block 元素之间会有一个空格字符。您可以通过将其父级的font-size 设置为0(或使用image replacement 技术)来删除它:

    #img_holder {
        font: 0/0 a;
        /* other styles... */
    }
    

    【讨论】:

    • 哇,我真笨。谢谢你,我完全错过了。当我阅读解释时,我也感到困惑,因为我想知道为什么回答该帖子的人谈论并排对齐元素。
    猜你喜欢
    • 1970-01-01
    • 2013-11-25
    • 2011-04-26
    • 1970-01-01
    • 2014-05-26
    • 2018-06-23
    • 2017-07-01
    • 1970-01-01
    • 2012-03-05
    相关资源
    最近更新 更多