前端面试基础必备

元素垂直与居中

2018-08-17  本文已影响3人  puxiaotaoc

一、元素垂直居中

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    .father {
      position: relative;
    }

    .child {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  </style>
</head>

<body>
  <div class="father">
    <div class="child">
      我是child
    </div>
  </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    .father {
      height: 200px;
      background: #333;
    }

    .child {
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }
  </style>
</head>

<body>
  <div class="father">
    <div class="child">
      我是child
    </div>
  </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    .father {
      display: flex;
      flex-direction: column;
      align-items: center; // 垂直居中
      justify-content: center; // 水平居中
      height: 200px;
    }
  </style>
</head>
<body>
  <div class="father">
    <div class="child">
      我是child
    </div>
  </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    .father {
      display: table-cell;
      vertical-align:middle;
      height: 200px;
    }
  </style>
</head>

<body>
  <div class="father">
    <div class="child">
      我是child
    </div>
  </div>
</body>
</html>

二、元素水平居中

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    .father {
      margin: auto;
      width: 200px;
    }
  </style>
</head>

<body>
  <div class="father">
    <div class="child">
      我是child
    </div>
  </div>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读