CSS 置中

CSS 置中是最常見的佈局需求之一,這篇介紹各種水平置中、垂直置中的方法。

水平置中

行內元素:text-align

對於行內元素(如文字、<span><a>),在父元素使用 text-align: center

.container {
  text-align: center;
}
<div class="container">
  <span>這段文字會置中</span>
</div>

區塊元素:margin auto

對於有固定寬度的區塊元素,使用 margin: 0 auto

.box {
  width: 300px;
  margin: 0 auto;
}

Flexbox

.container {
  display: flex;
  justify-content: center;
}

Grid

.container {
  display: grid;
  justify-items: center;
}

垂直置中

單行文字:line-height

line-height 等於容器高度:

.box {
  height: 100px;
  line-height: 100px;
}

Flexbox

.container {
  display: flex;
  align-items: center;
  height: 300px;
}

Grid

.container {
  display: grid;
  align-items: center;
  height: 300px;
}

絕對定位 + transform

.container {
  position: relative;
  height: 300px;
}

.centered {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

水平垂直同時置中

Flexbox(推薦)

最簡單直覺的方式:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

Grid(推薦)

.container {
  display: grid;
  place-items: center;
  height: 100vh;
}

place-items: center 等同於 justify-items: center + align-items: center

絕對定位 + transform

.container {
  position: relative;
  height: 100vh;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

絕對定位 + margin auto

元素需要有固定大小:

.container {
  position: relative;
  height: 100vh;
}

.centered {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 300px;
  height: 200px;
  margin: auto;
}

絕對定位 + inset + margin auto

.centered {
  position: absolute;
  inset: 0;
  width: 300px;
  height: 200px;
  margin: auto;
}

方法比較

方法適用情況需要知道尺寸
Flexbox現代瀏覽器不需要
Grid現代瀏覽器不需要
position + transform所有情況不需要
position + margin auto固定尺寸需要
text-align行內元素不需要
margin: 0 auto區塊水平置中需要寬度

實用範例

頁面內容置中

.page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

卡片內容置中

.card {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 40px;
}

圖示和文字對齊

.icon-text {
  display: flex;
  align-items: center;
  gap: 8px;
}

表單置中

.form-container {
  display: flex;
  justify-content: center;
  padding: 40px;
}

.form {
  width: 100%;
  max-width: 400px;
}

彈出視窗置中

.modal-container {
  position: fixed;
  inset: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0,0,0,0.5);
}

.modal {
  background: white;
  padding: 24px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
}

載入動畫置中

.loading-container {
  display: grid;
  place-items: center;
  height: 100vh;
}

Logo 置中

.header {
  display: flex;
  justify-content: center;
  padding: 16px;
}

/* 或使用 text-align */
.header {
  text-align: center;
  padding: 16px;
}