如何垂直居中元素

學習如何使用 CSS 將元素垂直和水平居中。

我是垂直和水平居中的。

如何垂直居中任意元素

實例

<style>
.container {
  height: 200px;
  position: relative;
  border: 3px solid green;
}
.vertical-center {
  margin: 0;
  position: absolute;
  top: 50%;
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}
</style>
<div class="container">
  <div class="vertical-center">
    <p>I am vertically centered.</p>
  </div>
</div>

親自試一試

如何垂直和水平居中

實例

<style>
.container {
  height: 200px;
  position: relative;
  border: 3px solid green;
}
.center {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
</style>
<div class="container">
  <div class="center">
    <p>I am vertically and horizontally centered.</p>
  </div>
</div>

親自試一試

您還可以使用 Flexbox 將元素居中:

實例

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  border: 3px solid green;
}

親自試一試

相關頁面

教程:CSS 對齊

教程:CSS 變換

教程:CSS Flexbox