css 如何使一个盒子水平垂直居中

本文介绍了使用CSS将一个盒子水平垂直居中的四种常见方法:1) 使用Flex布局;2) 利用定位和transform属性;3) 通过定位和margin负值;4) 使用display:table-cell。详细代码示例帮助理解每种方法的实现细节。

css 如何使一个盒子水平垂直居中

方法一、使用 flex 布局

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: brown;
+        display: flex;
+        justify-content: center;
+        align-items: center;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: cadetblue;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法二、使用定位和 transform

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: chocolate;
        position: relative;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: darkcyan;
        position: absolute;
        left: 50%;
        top: 50%;
+        transform: translate(-50%, -50%);
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法三、使用定位和 magin

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: chocolate;
        position: relative;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: darkcyan;
        position: absolute;
        left: 50%;
        top: 50%;
+        margin-top: -50px;
+        margin-left: -50px;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法四、使用 display:table-cell

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: chocolate;
+        display: table-cell;
+        vertical-align: middle;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: darkcyan;
+        margin: auto;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值