使用 jQuery 将网页水平和垂直居中
谁能告诉我这段代码有什么问题吗?我试图将我的网页垂直和水平居中,但这不起作用!它不以我为中心。
<html>
<head>
<title>String Functions</title>
<script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
<script type="text/javascript">
jQuery.fn.center = function() {
this.css("position", "absolute");
this.css("top", ($(document).height() - this.height()) / 2 + $(document).scrollTop() + "px");
this.css("left", ($(document).width() - this.width()) / 2 + $(document).scrollLeft() + "px");
return this;
};
$("#d1").center();
</script>
</head>
<body>
<div id="d1" style="background-color:red;width:100px; height: 100px;"></div>
</body>
Can anyone tell me whats wrong with this code? I'm trying to center my webpages vertically and horizontally but this isn't working! It's not centering for me.
<html>
<head>
<title>String Functions</title>
<script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
<script type="text/javascript">
jQuery.fn.center = function() {
this.css("position", "absolute");
this.css("top", ($(document).height() - this.height()) / 2 + $(document).scrollTop() + "px");
this.css("left", ($(document).width() - this.width()) / 2 + $(document).scrollLeft() + "px");
return this;
};
$("#d1").center();
</script>
</head>
<body>
<div id="d1" style="background-color:red;width:100px; height: 100px;"></div>
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个吧。
将绝对定位元素居中的一种非常可靠的方法是将其位置从左侧或顶部设置为 50%,然后将其边距设置为对象宽度或高度的一半。
Try this instead.
A very reliable way to center an absolutely positioned element is to set its position from the left or top to 50%, and then its margin to -half the width or height of the object.