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>
Try this instead.
jQuery.fn.center = function() {
this.css({
"position" : "absolute",
"top" : "50%",
"left" : "50%",
"margin-left" : (this.width() / 2) * -1,
"margin-top" : (this.width() / 2) * -1
});
};
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.
精彩评论