居中是 CSS 最經典的難題之一。除了常見的負 margin 與 translate 位移法,還有一種組合了表格式對齊與絕對定位的寫法,同時兼顧 IE 與 Firefox。
CSS 程式碼如下:
以下是代碼片段:
div {
width:300px;
height:300px;
border:1px solid #c00;
position:relative; /* to IE */
display:table-cell;
text-align:center;
vertical-align:middle; /* to firefox */
}
div p {
position:static !important;
position:absolute;
top:50%; /* 讓 IE 上空出 50% */
border: 1px solid #CCCCCC;
}
div p img { /* 讓 img 在 div 中居中 */
position:static !important;
position:relative;
top:-50%; /* IE 向上 -50% */
left:-50%; /* IE 向左 -50% */
border: 2px solid #0099CC;
}
div p span { /* 讓文字在 div 中居中 */
position:static !important;
position:relative;
top:-50%; /* IE 向上 -50% */
left:-50%; /* IE 向左 -50% */
border: 2px solid #0099CC;
}
對應的 HTML 結構如下:
以下是代碼片段:
<!-- 圖片垂直居中 -->
<div><p>
<img src="https://www.poluoluo.com/poimg/2008logo.gif" />
</p></div>
<!-- 文字垂直居中 -->
<div><p>
<span>文字垂直居中</span>
</p></div>
整體思路是:外層容器用 position:relative 搭配 display:table-cell 與 vertical-align:middle 處理 Firefox 的垂直居中;內層元素先用 top:50% 把頂點推到中央,再用 top:-50% 往上拉回自身高度的一半,藉此完成居中。!important 與重複宣告的 position,則是用來繞過 IE 的解析順序問題。