代码描述:JavaScript 未知高度 div垂直居中。JavaScript未知高度div垂直居中
如果在不知道div高度的情况下将其在父元素中实现它的垂直居中对齐有难度,因为涉及到浏览器兼容性,下面就介绍一下通过js让未知高度的div在父元素中垂直居中,代码如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="author" content="http://www.51qianduan.com/" /> <title>51前端</title> <style type="text/css"> #parent{ width:200px; height:200px; background-color:red; overflow:hidden; } #children{ width:60px; height:60px; background-color:green; margin:0px auto; } </style> <script type="text/javascript"> window.onload=function(){ var parentH=document.getElementById("parent").offsetHeight; var childrenH=document.getElementById("children").offsetHeight; document.getElementById("children").style.marginTop=((parentH-childrenH)/2)+"px"; } </script> </head> <body> <div id="parent"> <div id="children"></div> </div> </body> </html>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能