Rumah >hujung hadapan web >html tutorial >div永远居中,css和js代码_html/css_WEB-ITnose
//css方式<br /><!DOCTYPE html><html><head> <meta charset="utf-8"> <title>CSS Position 定位实现 DIV 在窗口居中</title> <style type="text/css"> .dialog { position: fixed; _position: absolute; z-index: 1; top: 50%; left: 50%; margin: -141px 0 0 -201px; width: 400px; height: 280px; border: 1px solid #CCC; line-height: 280px; text-align: center; font-size: 14px; background-color: #F4F4F4; overflow: hidden; } </style></head><body style="height:5000px;"> <div class="dialog">我是css居中</div></body></html>
//js方式<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>jq DIV 在窗口居中</title> <script src="Scripts/jquery-1.8.2.js"></script> <style type="text/css"> .dialog { position: absolute; z-index: 1; width: 400px; border: 1px solid #CCC; line-height: 280px; text-align: center; font-size: 14px; background-color: #F4F4F4; overflow: hidden; } </style></head><body style="height:5000px;"> <div class="dialog">我是js居中</div></body></html><script> $(function () { Loading($('.dialog')); $(window).scroll(function () { Loading($('.dialog')); }); $(window).resize(function () { Loading($('.dialog')); }); //弹出居中 function Loading($obj) { //获取元素自身的宽度 var L1 = $obj.width(); //获取元素自身的高度 var H1 = $obj.height(); //获取实际页面的left值。(页面宽度减去元素自身宽度/2) var Left = (document.documentElement.clientWidth - L1) / 2; //获取实际页面的top值。(页面宽度减去元素自身高度/2) var top = (document.documentElement.clientHeight - H1) / 2 + $(document).scrollTop(); $obj.css({ left: Left + 'px', top: top + 'px' }); } })</script>