問題描述

我有一個 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇