萬盛學電腦網

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

CSS 元素水平垂直置中四大經典方案完整對比

方案一:table-cell(IE8+)

.container { display: table-cell; vertical-align: middle; text-align: center; width: 400px; height: 300px; border: 1px solid #ccc; }
.container img { vertical-align: middle; max-width: 100%; max-height: 100%; }

優點:單層結構、垂直置中語義明確。缺點:IE7- 不支援、無法配合 absolute 子元素彈性定位。

方案二:相對定位 + 負 margin(需知寬高)

.parent { position: relative; width: 300px; height: 200px; border: 1px solid #ccc; }
.child  { position: absolute; top: 50%; left: 50%; width: 240px; height: 140px; margin: -70px 0 0 -120px; background: #ccc; }

優點:IE6+ 全支援。缺點:需預知子元素尺寸、結構較深。

方案三:line-height 單行文字垂直置中

.title { height: 55px; line-height: 55px; text-align: center; border: 1px solid #ccc; }

優點:極簡、全瀏覽器支援。缺點:僅限單行文字、高度固定。

方案四:絕對定位 + margin: auto(現代推薦,IE9+)

.parent { position: relative; width: 300px; height: 200px; border: 1px solid #ccc; }
.child  { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; width: 240px; height: 140px; background: #ccc; }

優點:不需知寬高(若寬高為 auto 需配合具體尺寸)、程式碼簡潔。缺點:IE8- 不支援四向定位 + margin auto。

方案五:Flexbox(現代首選,IE10+)

.center { display: flex; align-items: center; justify-content: center; min-height: 200px; }

優點:單層、不需知尺寸、支援多行、響應式友善。缺點:IE10 需 -ms- 前綴,IE9- 不支援。

方案六:Grid(最簡潔,現代瀏覽器)

.center { display: grid; place-items: center; min-height: 200px; }

選型決策樹

  • 需支援 IE8- → 方案二(負 margin)或表格佈局。
  • 僅現代瀏覽器 → **Flexbox** 或 **Grid** 首選。
  • 單行文字 → 方案三(line-height)。
  • 圖片/多媒體置中容器 → 方案一(table-cell)或 Flex。
copyright © 萬盛學電腦網 all rights reserved