未知大小的父元素如何实现让子元素水平垂直居中?

x33g5p2x  于2022-03-22 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(175)

一、写在前面
今天看到一个面试题,问未知大小的父元素如何实现让其子元素水平垂直居中。现在总结一下几种方法。
二、实现方法
2.1、flex布局

<!DOCTYPE html>
<html lang="cn">

<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>
    .parent {
      width: 200px;
      height: 200px;
      background-color: red;
      display:flex;
      justify-content: center;
      align-items: center;
    }
  </style>
</head>

<body>

  <div class="parent">
    <div class="child">hello world</div>
  </div>

</body>

</html>

2.2、使用table布局

<!DOCTYPE html>
<html lang="cn">

<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>
    .parent {
      width: 200px;
      height: 200px;
      display: table;
      background-color: red;
    }

    .child {
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }
  </style>
</head>

<body>

  <div class="parent">
    <div class="child">hello world</div>
  </div>

</body>

</html>

2.3、transform

<!DOCTYPE html>
<html lang="cn">

<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>
    .parent {
      width: 200px;
      height: 200px;
      background-color: red;
      position: relative;
    }

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

<body>

  <div class="parent">
    <div class="child">hello world</div>
  </div>

</body>

</html>

2.4、

相关文章

微信公众号

最新文章

更多