垂直和水平居中,無需擔心高度或寬度

以下技術允許你將內容新增到 HTML 元素並將其水平和垂直居中,而不必擔心其高度或寬度

外容器

  • 應該有 display: table;

內部容器

  • 應該有 display: table-cell;
  • 應該有 vertical-align: middle;
  • 應該有 text-align: center;

內容框

  • 應該有 display: inline-block;
  • 應重新調整水平文字對齊,例如。text-align: left;text-align: right;,除非你希望文字居中

演示

HTML

<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        You can put anything here!
     </div>
   </div>
</div>

CSS

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding: 20px;
    border: 1px solid #000;
}

另見這個小提琴