天天看點

CSS 元素垂直和水準居中

1、居于文檔中間

如果讓一個元素居于html文檔中間,可以使用如下代碼:

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">

    <title>測試</title>
    <style>
        html,body{
          height: 100%;
        }
        .center-content {
          position : absolute;
          top: 50%;
          left:50%;
          transform: translate(-50%, -50%);
        }
    </style>
  </head>
  <body>
    <div class="center-content" style="width: 20%;height: 20%;background-color: black;">
    </div>
  </body>
</html>