欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

9种方法:在CSS中实现水平垂直居中

最编程 2024-01-12 09:00:13
...

一、水平垂直居中 9 种方法汇总

有哪些方法?

父、子元素宽高未知时

  1. table-cell(使用表格样式)
  2. flex 布局(父级 justify-content: center 和 align-items: center 即可)
  3. absolute + transform(定位的上、左为 50%,translate 上、左负 50%)
  4. absolute + margin: auto(定位的上下左右为 0)
  5. Grid 网格布局
  6. 直接使用 table(改变结构实现,和第一条类似)

子元素固定宽高已知时(假设子元素宽高为 200px)

  1. absolute + calc(定位上、左负50%时减去子元素宽、高)
  2. absolute + 负margin(定位的上、左为 50%,margin 的上、左负子元素的一半)

父元素高度已知(假设为 400px),子元素宽高未知

  1. text-align + vertical-align

初始化测试代码

HTML 测试代码,默认父子元素宽高未知。

<!DOCTYPE html>
<html lang="en">
<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>Demo</title>
</head>
<body>
  <div class="parent">
    <div class="children"></div>
  </div>

  <style>
  .parent {
    width100%;
    height50%;
    background-color: skyblue;
  }
  .children {
    width20%;
    height20%;
    background-color: pink;
  }
  </style>
</body>
</html>

二、父、子元素宽高未知(6 种)

第一种:table-cell

.parent {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.children {
  display: inline-block;
}

第二种:flex 布局(两种办法)

① 只设置父元素

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

② 同时设置父子元素

.parent {
  display: flex;
}
.children {
  align-self: center;
  margin: auto;
}

第三种:absolute + transform

.parent {
  position: relative;
}
.children {
  position: absolute;
  top50%;
  left50%;
  transformtranslate(-50%, -50%);
}

第四种:absolute + margin: auto

.parent {
  position: relative;
}
.children {
  position: absolute;
  top0;
  left0;
  right0;
  bottom0;
  margin: auto;
}

第五种:Grid 布局

.parent {
  display: grid;
}
.children {
  align-self: center;
  justify-self: center;
}

第六种:直接使用 table(改变结构实现,和第一条类似)

HTML 代码

<table>
  <tbody>
    <tr>
      <td class="parent">
        <div class="children"></div>
      </td>
    </tr>
  </tbody>
</table>

CSS 代码

.parent {
  text-align: center;
}
.children {
  display: inline-block;
}

三、子元素宽高已知(假设子元素宽高为 200px)

第一种:absolute + calc

.parent {
  position: relative;
}
.children {
  position: absolute;
  topcalc(50% - 100px);
  leftcalc(50% - 100px);
}

第二种:absolute + 负 margin

.parent {
  position: relative;
}
.children {
  position: absolute;
  top50%;
  left50%;
  margin-top: -100px;
  margin-left: -100px;
}

四、父元素高度已知(假设为 400px),子元素宽高未知

第一种:text-align + vertical-align

.parent {
  text-align: center;
  line-height400px;
}
.children {
  display: inline-block;
  vertical-align: middle;
  line-height: initial;
}