第一种方式

margin 实现水平方向居中,table-cell + vertical-align 实现垂直方向居中;

<head>
  <style>
    #parent11 {
      width: 300px;
      height: 150px;
      background-color: greenyellow;
      display: table-cell; /* display: table-cell,相当于 td 元素 */
      vertical-align: middle; /* vertical-align 控制垂直居中 */
    }
    #child11 {
      width: 100px;
      height: 100px;
      background-color: green;
      margin: auto; /* margin 控制水平居中 */
    }
  </style>
</head>
<body>
  <div id="parent11">
    <div id="child11"></div>
  </div>
</body>

第二种方式

absolute + transform/margin 实现水平方向和垂直方向居中;

  1. 解决方案一:left: 0; right: 0; top: 0; bottom: 0; margin: auto;
  2. 解决方案二:left: 50%; top: 50%; margin: -100px 0 0 -100px;
  3. 解决方案三:left: 50%; top: 50%; transform: translate(-50%,-50%);
<head>
  <meta charset="UTF-8">
  <title></title>
  <style>
    #parent12, #parent13, #parent14 {
      width: 300px;
      height: 150px;
      background-color: greenyellow;
      position: relative;
      margin-bottom: 5px;
    }
    #child12 {
      width: 100px;
      height: 100px;
      background-color: green;
      position: absolute;
      /* 解决方案一:left: 0; right: 0; top: 0; bottom: 0; margin: auto; */
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
    }
    #child13 {
      width: 100px;
      height: 100px;
      background-color: green;
      position: absolute;
      /* 解决方案二:left: 50%; top: 50%; margin: -50px 0 0 -50px; */
      left:50%; 
      top:50%; 
      margin:-50px 0 0 -50px; 
    }
    #child14 {
      width: 100px;
      height: 100px;
      background-color: green;
      position: absolute;
      /* 解决方案三:left: 50%; top: 50%; transform: translate(-50%,-50%); */
      left:50%; 
      top:50%; 
      transform: translate(-50%,-50%);
    }
  </style>
</head>
<body>
  <div id="parent12">
    <div id="child12"></div>
  </div>
  <div id="parent13">
    <div id="child13"></div>
  </div>
  <div id="parent14">
    <div id="child14"></div>
  </div>
</body>

第三种方式

flex + justify-content + align-items 实现水平方向和垂直方向居中;

<head>
  <meta charset="UTF-8">
  <title></title>
  <style>
    #parent15 {
      width: 300px;
      height: 150px;
      background-color: greenyellow;
      display: flex;
      justify-content: center; /* 控制水平居中 */
      align-items: center; /* 控制垂直居中 */
    }
    #child15 {
      width: 100px;
      height: 100px;
      background-color: green;
    }
  </style>
</head>
<body>
  <div id="parent15">
    <div id="child15"></div>
  </div>
</body>
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于产品、设计、开发的问题和看法,还有技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程

了解更多

目录

  1. 1. 第一种方式
  2. 2. 第二种方式
  3. 3. 第三种方式