相容所有瀏覽器長寬自適應元素垂直水平居中

antzone發表於2017-03-15

固定寬度的子元素垂直水平居中效果是非常的容易實現的,這裡不多介紹了,具體可以參閱css實現div水平垂直居中程式碼一章節,如果不是固定的那就有點麻煩,當然在標準瀏覽器中是沒問題, 但是如果要相容所有瀏覽器就比較麻煩了,下面介紹一下使用js實現此功能的程式碼。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#box{
  height:300px;
  width:300px;
  border:1px solid;
  position:relative;
}
#inner{
  background-color:red;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var box=document.getElementById("box");
  var inner=document.getElementById("inner");
  var w=inner.offsetWidth;
  var h=inner.offsetHeight;
  inner.style.position="absolute";
  inner.style.left="50%";
  inner.style.top="50%";
  inner.style.marginLeft="-"+parseInt(w/2)+"px";
  inner.style.marginTop="-"+parseInt(h/2)+"px";
}
</script>
</head>
<body>
<div id="box">
  <span id="inner">內容自適應水平垂直居中</span>
</div>
</body>
</html>

以上程式碼實現了我們的要求,內碼表比較簡單,這裡就不細說了,可以參閱相關閱讀。

相關閱讀:

1.offsetWidth屬性可以參閱offsetWidth一章節。

2.parseInt()函式可以參閱javascript parseInt()一章節。

相關文章