下文以span元素為例子,介紹一下如何實現span元素在div中實現水平垂直居中效果,代碼如下:
<!DOCTYPE html><html><head><meta charset=" utf-8"><meta name="author" content="http://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元素的左上角垂直水平居中,然后在設置span元素的負的外邊距,尺寸是span元素寬高的一半,這樣就實現了垂直水平居中效果。
以上就是本文的全部內容,今天就到此為止,后續給大家更新scrollTop、offsetHeight和offsetTop等屬性用法詳解,請持續關注本站,謝謝。
新聞熱點
疑難解答