萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 讓 DIV 水平垂直置中完全指南:Margin Auto、定位法、JS 輔助

一、水平置中:標準流方案

/* 父容器 */
body { text-align: center; }           /* IE5.x 相容 */
/* 子容器 */
#center { margin-left: auto; margin-right: auto; width: 940px; }
  • 必須指定 width。
  • 需正確 DOCTYPE 觸發標準模式。
  • 全頁置中建議拆分多層 div,各層加 margin:auto,避免單層過寬。

垂直置中:行高法(單行文字/行內元素)

#center {
  height: 200px;
  line-height: 200px;   /* 等於容器高度 */
  vertical-align: middle;
  text-align: center;
}

將行高撐滿容器,行內內容自動垂直置中。僅限單行。

垂直置中:背景圖法(裝飾性圖片)

body { background: url(bg.jpg) #fff no-repeat center; }

center 關鍵字同時水平垂直置中背景圖。可用 top left、50% 30% 等精確控制。

二、JS 動態置中(響應視窗變化)

<div id="L1" style="position:absolute;">內容</div>
<script>
function moveIt() {
  L1.style.left = (document.body.offsetWidth - L1.offsetWidth) / 2 + document.body.scrollLeft;
  L1.style.top  = (document.body.offsetHeight - L1.offsetHeight) / 2 + document.body.scrollTop;
}
window.onload = window.onresize = window.onscroll = moveIt;
</script>

適用於彈窗、Loading 等需隨時置中的絕對定位層。

三、CSS 絕對定位置中(已知寬高)

#box {
  position: absolute;
  left: 50%; top: 50%;
  width: 740px; height: 340px;
  margin-left: -370px;  /* -width/2 */
  margin-top: -170px;   /* -height/2 */
  background: #f00;
}

原理: 左上角對齊視窗中心 → 負邊距拉回自身高寬一半 → 幾何中心重合。缺點: 需知寬高,內容超出會溢出。

四、現代最佳:Flexbox(未知寬高、響應式)

.center-container {
  display: flex;
  justify-content: center;  /* 水平 */
  align-items: center;      /* 垂直 */
  min-height: 100vh;        /* 全螢幕高 */
}

IE10+ 完美支援,無需知寬高、無溢出風險、代碼最少。現代專案首選。

copyright © 萬盛學電腦網 all rights reserved