用絕對定位把元素左上角挪到 50%,再用負 margin 拉回一半寬高,元素就精準落在正中央。
<style type="text/css">
#divcenter {
position: absolute; /* 讓層漂浮起來 */
top: 50%;
left: 50%;
width: 300px;
height: 300px;
margin-top: -150px; /* 必須是高度的一半 */
margin-left: -150px; /* 寬度的一半 */
background: yellow;
border: 1px solid red;
}
</style>
<div id="divcenter">this is a test</div>
<script type="text/javascript">
function cen() {
var divname = document.all("testdiv");
// 居中高度 = (頁面高度 - DIV 高度) / 2
var topvalue = (document.body.clientHeight - divname.clientHeight) / 2;
divname.style.marginTop = topvalue;
}
window.onresize = cen; // 視窗尺寸變化時重新計算
</script>
<body style="height:100%; width:100%; text-align:center;" onload="cen()">
<div id="testdiv" style="margin:0 auto; border:1px solid red; height:400px; width:400px;">
DIV 居中演示
</div>
</body>
<div style="position:absolute; top:50%; height:240px; border:1px solid red;
margin:0 auto; margin-top:-120px; width:300px; left:50%; margin-left:-150px;"></div>
利用 table-cell 搭配定位 hack,可同時兼顧 IE5.5~IE8 與 Firefox、Opera、Safari:
<style type="text/css">
.img_v {
display: table-cell !important;
display: block;
position: static !important;
position: relative;
overflow: hidden;
width: 400px; height: 400px;
border: 1px solid #000;
vertical-align: middle;
text-align: center;
}
.img_v p {
display: table-cell !important;
display: block;
margin: 0;
position: static !important;
position: absolute;
top: 50%; left: 50%;
width: 400px;
margin-left: auto; margin-right: auto;
}
.img_v img {
position: static !important;
position: relative;
top: auto !important; top: -50%;
left: auto !important; left: -50%;
}
</style>
<div class="img_v"><p><img src="https://www.jb51.net/images/logo.gif"></p></div>
現代專案其實不必這麼辛苦:flex 的 display:flex; justify-content:center; align-items:center; 三行就能完成,且不必知道元素尺寸;若只是單一行列置中,grid 的 place-items:center 更簡潔。上面幾種寫法的價值在於理解定位與盒模型的運作,以及維護舊系統時派得上用場。