css設置div垂直居中

一開始想着直接對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

})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章