代码
提交代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* 清除默认样式 */ * { padding: 0; margin: 0; } /* 令html和body全屏显示, 并有一个灰色背景 */ html, body { height: 100%; background: gray; } /* 在祖先元素上设置相对定位 */ body { position: relative } .center { /* 绝对定位 */ position: absolute; /* 左方为50% */ left: 50%; /* 给个宽高方便查看 */ width: 90%; height: 100%; /* 这个50%是相对于自身宽高而言的 */ transform: translate(-50%); /* 白色背景 */ background: white; } </style> </head> <body> <div class="center"></div> </body> </html>
运行结果