一开始想着直接对div用margin-top:50%就行了,但不知道为什么会移到很下面,margin-top:12.5%才刚好居中,这个问题暂时还没有解决。

这里介绍的方法是使用top和transform来实现div的一个居中。

html文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="${pageContext.request.contextPath }/css/index.css">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath }/js/height.js"></script>
<title>首页</title>
</head>
<body>
	<div class="page">
		<form action="">
			<table>
				<tr>
					<td></td>
					<td><strong>用户登录</strong></td>
				</tr>
				<tr>
					<td><label for="id">用户名:</label></td>
					<td><input type="text" class="form-control" name="id" id="id"/></td>
				</tr>
				<tr>
					<td><label for="pwd">密码:</label></td>
					<td><input type="password" class="form-control" name="pwd" id="pwd"/></td>
				</tr>
				<tr>
					<td></td>
					<td><button type="submit" class="btn">登录</button></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

css文件

html,body{width:100%;height:100%;padding:0;margin:0;}
.page{width:280px;height:215px;border:1px #CCCCCC solid;padding:20px 30px;margin:0px auto;font-size:15px;top:50%;transform:translateY(-50%);position:relative;}
.page td{padding:8px 3px;font-size: 13px;}
.page input{width:130px;height:20px;font-size:13px;}
.page button{font-size:13px;}

这里有几个要注意的点:
1.html 和 body 标签需要设置高度百分之百,并且将padding和margin清除,不然会有滚动条
2.div的position不能用默认的static,static是不能移动的,这里不需要使用absolute和fixed,因为relative是不会使元素脱离文档流的,absolute和fixed则会。所以这里使用relative就行了
3.这里的原理是想下移动父级div高度的50%,即top:50%
然后再将div向上移动它的高度的50%,即transform:translateY(-50%),这样就实现了一个垂直居中的效果

在寻找方法的时候,找了下怎么用jquery获取窗口的height,这里也和大家分享一下:

$(document).ready(function(){
alert($(window).height()); //浏览器当前窗口可视区域高度
alert($(document).height()); //浏览器当前窗口文档的高度
alert($(document.body).height());//浏览器当前窗口文档body的高度
alert($(document.body).outerHeight(true));//浏览器当前窗口文档body的总高度 包括border padding margin

alert($(window).width()); //浏览器当前窗口可视区域宽度
alert($(document).width());//浏览器当前窗口文档对象宽度
alert($(document.body).width());//浏览器当前窗口文档body的宽度
alert($(document.body).outerWidth(true));//浏览器当前窗口文档body的总宽度 包括border padding margin

})