方法 1:Flexbox 置中

HTML
<div class="parent">
<div class="child">
我是被置中的區塊
</div>
</div>
CSS
.parent {
/* 父容器的尺寸,示範用全螢幕高度 */
width: 100%;
height: 100vh;
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
background: #f0f0f0;
}
.child {
width: 200px;
height: 100px;
background: #ccc;
text-align: center;
line-height: 100px; /* 僅示範用,調整文字垂直置中 */
}
- 重點:
- justify-content: center → 水平置中
- align-items: center → 垂直置中
- 父容器 display: flex;
- 注意:
- 父容器必須有明確高度(此例示範 100vh)。
方法 2:Absolute + transform 置中
HTML
<div class="parent">
<div class="child">
我是被置中的區塊
</div>
</div>
CSS
.parent {
position: relative; /* 作為定位參考 */
width: 100%;
height: 100vh;
background: #f0f0f0;
}
.child {
position: absolute;
top: 50%;
left: 50%;
/* transform 讓元素往回移動自己一半的寬高,即達到正中央 */
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
background: #ccc;
text-align: center;
line-height: 100px;
}
- 重點:
- 使用 position: absolute; 並將 top、left 設為 50%。
- transform: translate(-50%, -50%) 讓元素往左、往上移動自身寬高的一半,對準正中央。
- 注意:
- 父容器一定要有 position: relative; 或其他非 static 定位。
- 同樣需要父容器有固定高度或尺寸。
方法 3:CSS Grid 置中
HTML
<div class="parent">
<div class="child">
我是被置中的區塊
</div>
</div>
CSS
.parent {
display: grid;
width: 100%;
height: 100vh;
background: #f0f0f0;
/* place-items: center; 等同於 justify-content + align-content 都是 center */
place-items: center;
}
.child {
width: 200px;
height: 100px;
background: #ccc;
text-align: center;
line-height: 100px;
}
- 重點:
- display: grid; place-items: center; 可同時達到水平、垂直置中。
- 或者使用 justify-content: center; align-items: center; 替代。
- 注意:
- CSS Grid 在 IE11 或更舊的瀏覽器支援度較差,但在現代瀏覽器已普遍可用。
方法 4:只有水平置中 (常見做法)
若只需要水平置中「塊級元素」,一種傳統作法是 margin: 0 auto;
<div class="container">
<div class="child">我只要水平置中</div>
</div>
.container {
width: 100%;
background: #f0f0f0;
}
.child {
width: 300px;
margin: 0 auto; /* 水平置中 */
background: #ccc;
}
- 垂直置中則還需要依賴其他方式(Flex、absolute、Grid 等)。
總結
- Flexbox:最直覺、最常用於水平+垂直置中。
- Absolute + transform:在舊一點的瀏覽器也能用,但需要父容器 position: relative;。
- CSS Grid:簡潔強大,但需注意瀏覽器支援度(現代版本已無大礙)。
- margin: 0 auto;:僅限塊級元素(block element)做「水平置中」,無法處理垂直。