DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
用絕對定位實作水平與垂直居中:文字與圖片通用寫法
編輯:CSS進階教程     

居中是 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 的解析順序問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved