问题描述

我有一个 200 x 200 像素的 div 。我想把一个 50 x 50 像素的图像放在 div 的中间。

怎么办?

我可以使用 text-align: center 作为 div 来使其居中。但垂直对齐是问题..

最佳解决方案

就个人而言,我将其作为 div 中的背景图像,其中的 CSS 为:

#demo {
    background: url(bg_apple_little.gif) no - repeat center center;
    height: 200px;
    width: 200px;
}

(假设您已经指定了 heightid="demo",并且 width 添加 background 不应该是一个问题)

让浏览器承受压力。

次佳解决方案

在旧版浏览器中工作 (IE> = 8)

绝对位置与自动边距组合允许水平和垂直居中。元素位置可以基于使用相对定位的父元素位置。 View Result

img {
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

来源:Centering documentation page

第三种解决方案

当然,也可以用 valign 创建 table 。无论你知道 div 的高度还是不知道,这都会奏效。

<div>
   <table width="100%" height="100%" align="center" valign="center">
   <tr><td>
      <img src="foo.jpg" alt="foo" />
   </td></tr>
   </table>
</div>

但是,只要有可能,您应始终坚持使用 css

第四种方案

我会用 position:relative; 设置你的更大的 div,然后为你的图像做到这一点:

img.classname{
   position:absolute;
   top:50%;
   left:50%;
   margin-top:-25px;
   margin-left:-25px;
}

这只能工作,因为你知道图像和包含 div 的尺寸。这也将让你有其他项目在包含 div … 其中的解决方案,如使用 line-height 不会。

编辑:注意… 您的边距是图像大小的负半数。

第五种方案

这样做正确:

display: block;
margin-left: auto;
margin-right: auto

否则尝试这个,如果上面只给你水平居中:

.outerContainer {
   position: relative;
}

.innerContainer {
   width: 50px; //your image/element width here
   height: 50px; //your image/element height here
   overflow: auto;
   margin: auto;
   position: absolute;
   top: 0; left: 0; bottom: 0; right: 0;
}

第六种方案

这是一个晚了,但这是一个解决方案,我用来垂直对齐父 div 中的元素。

当您知道容器 div 的大小而不是包含的图像的大小时,这很有用。 (通常情况下,使用灯箱或图像转盘) 。

这是您应该尝试的样式:

 container div
 {
   display:table-cell;
   vertical-align:middle;

   height:200px;
   width:200px;
 }

 img
 {
   /*Apply any styling here*/
 }

第七种方案

这是另一种将任何东西都集中在一起的方法。

工作小提琴

HTML((如以往简单)

<div class="Container">
    <div class="Content"> /*this can be an img, span, or everything else*/
        I'm the Content
    </div>
</div>

CSS:

.Container
{
    text-align: center;
}

    .Container:before
    {
        content: '';
        height: 100%;
        display: inline-block;
        vertical-align: middle;
    }

.Content
{
    display: inline-block;
    vertical-align: middle;
}

Benefits

容器和内容高度未知。

定心没有特定的负边距,没有设置 line-height(所以它适用于多行文本),没有脚本,也可以很好的 CSS 过渡。

第八种方案

我发现,上面的 Valamas 和 Lepu 的答案是处理未知尺寸或已知尺寸的图像的最简单的答案,您不希望 hard-code 进入您的 CSS 。我只需要几个小小的调整:删除不相关的样式,将其大小调整为 200px 以匹配问题,并添加 max-height /max-width 来处理可能太大的图像。

div.image-thumbnail
{
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
}
div.image-thumbnail img
{
    vertical-align: middle;
    max-height: 200px;
    max-width: 200px;
}

第九种方案

Vertical-align 是最被滥用的 CSS 样式之一。对于不是 td 或 css“显示:table-cell” 的元素,您可能会期望什么。

这是一个很好的帖子。 http://phrogz.net/CSS/vertical-align/index.html

最常见的方法来实现您要查找的内容:

  • 填充顶部/底部

  • 绝对位置

  • line-height

第十种方案

在 CSS 中做为:

img
{

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

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛