<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/*
width 和 height 一定要设置,
100% 将元素填充整个页面,
如果是在其他元素内,不需要设置成 100%
*/
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
div {
/*
width 和 height 要设置,
transform 要通过该值去计算偏移
*/
width: 400px;
height: 300px;
margin: 0;
padding: 0;
border: 1px solid #ccc;
/*
设置相对定位,
相对父元素,这里是 body 元素,进行上,左偏移
*/
position: relative;
top: 50%;
left: 50%;
/*
相对于此元素 width 和 height 的值,
进行偏移
*/
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div>
</div>
</body>
</html>
- 示例