绝对定位 + 平移
平移是 CSS3 的,它可以按照自身尺寸的百分比来进行平移。
语法是:transform: translate(xx%);
<!DOCTYPE html>
<html lang="en">
<head>
< charset="UTF-8">
< name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 清除认样式 */
* { padding: ; margin: ; }
/* 令html和body全屏, 并有灰色背景 */
html, body { height: ; background: gray; }
/* 在祖先元素上设置相对定位 */
body { position: relative }
.center {
/* 绝对定位 */
position: absolute;
/* 左方为50% */
left: ;
/* 给个宽高方便查看 */
width: ;
height: ;
/* 这个50%是相对于自身宽高而言的 */
transform: translate(-);
/* 白色背景 */
background: white;
}
</style>
</head>
<body>
<div class="center"></div>
</body>
</html>
运行结果:
只要涉及到绝对定位,就一定要记得在祖先元素上设置相对定位或其他定位。
不然的话可能不会按照你想要的方式去执行哦。
下一小节我们来讲解网格实现法。