---
title: "JQ 页面上下左右居中的插件"
author: "onestopweb"
date: "2017-12-22T16:58:44Z"
tags: []
categories: ["Web前端"]
slug: "jq"
draft: false
lastmod: "2017-12-22T16:58:44Z"
id: 2405481
url: "https://onestopweb.iteye.com/blog/2405481"
---

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
body,div{ margin:0; padding:0;}
.box{ width:200px; height:60px; background-color:#c00;}
</style>
</head>
<body>
<div class="box"></div>
<script>window.jQuery || document.write(unescape("%3Cscript src='http://libs.baidu.com/jquery/1.10.1/jquery.min.js' type='text/javascript'%3E%3C/script%3E")); </script>
<script type="text/javascript">
jQuery.fn.center = function(){
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
    return this;
}
$(".box").center();
</script>
</body>
</html>
```

 

效果图：  
![](http://dl2.iteye.com/upload/attachment/0128/2598/2ba03eec-ce89-31ae-a8f0-2799f77b4479.png)