版面在 IE、Firefox 皆能置中,唯獨 Chrome 失效?這是經典的 CSS Hack 場景。只需在容器加入雙邊距自動,即可跨瀏覽器完美置中。
使用 text-align: center 或 IE 專屬 Hack(_、!important)在舊版瀏覽器置中,但 Chrome 不認這套,導致版面左偏。
.Google-center {
width: 320px;
height: 202px;
text-align: center; /* 內容文字置中 */
margin-left: auto; /* 關鍵:左邊距自動 */
margin-right: auto; /* 關鍵:右邊距自動 */
color: #ff33ff;
background-color: #ccffcc;
}
原理:區塊級元素設定寬度後,左右 margin: auto 會自動分配剩餘空間,使元素水平置中。此為 CSS2.1 標準,所有現代瀏覽器(含 Chrome、Edge、Safari、Firefox、IE8+)完整支援。
line-height = heightdisplay: flex; align-items: center; justify-content: center;position: absolute; top: 50%; transform: translateY(-50%);margin: 0 auto。width 或 max-width。text-align: center,子層加上 display: inline-block 亦可置中。