下面以 span 元素為例,介紹如何讓 span 元素在 div 中達成水平垂直居中,程式碼如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="https://www.softwhy.com/" /> <title></title> <style type="text/css"> #box{ width:200px; height:150px; background:blue; position:relative; } #antzone{ background:green; } </style> <script type="text/javascript"> window.onload=function(){ var obox=document.getElementById("box"); var oantzone=document.getElementById("antzone"); var w=oantzone.offsetWidth; var h=oantzone.offsetHeight; oantzone.style.position="absolute"; oantzone.style.left="50%"; oantzone.style.top="50%"; oantzone.style.marginLeft=-(w/2)+"px"; oantzone.style.marginTop=-(h/2)+"px"; } </script> </head> <body> <div id="box"> <spanj id="antzone"></span> </div> </body> </html>
上面的程式碼就完成了 span 元素在 div 中的水平垂直居中,接著說明它的實作過程。
一、實作原理:雖然 CSS 沒有明確給出 span 元素的尺寸,但它畢竟還是有尺寸的,而這個尺寸可以用 offsetWidth 與 offsetHeight 屬性取得。接著把 span 設為絕對定位,並將 left、top 都設為 50%,此時居中的其實是 span 的左上角而非中心點;因此再幫它設定「負的外邊距」,數值為 span 寬高的一半,如此一來就能讓中心點精準對齊,達成水平垂直居中的效果。
以上就是本文的全部內容,後續還會為大家更新 scrollTop、offsetHeight 與 offsetTop 等屬性的用法詳解,敬請持續關注本站,謝謝。