gpt4 book ai didi

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

转载 作者:知者 更新时间:2024-03-13 03:43:45 27 4
gpt4 key购买 nike

一、写在前面
今天看到一个面试题,问未知大小的父元素如何实现让其子元素水平垂直居中。现在总结一下几种方法。
二、实现方法
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、

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com