参考资料

  1. id选择器详细说明以及案例
  2. Vanta.js 如何与 CSS 过渡结合?
  3. css阴影效果属性
  4. flex-wrap: wrap/nowrap详细说明
  5. 有没有现成的Vanta.js与CSS过渡模板?
  6. css中div居中详细说明
  7. 如何提高Flex布局的性能?详细说明
  8. 如何避免 CSS 过渡动画卡顿?

CSS Div居中对齐方式

水平居中

  1. 使用margin: auto

.center-div {
  width: 200px;
  margin: 0 auto;
}
  1. 使用flexbox

.parent {
  display: flex;
  justify-content: center;
}
  1. 使用grid

.parent {
  display: grid;
  place-items: center;
}
  1. 使用text-align (内联元素)

.parent {
  text-align: center;
}

垂直居中

  1. 使用flexbox

.parent {
  display: flex;
  align-items: center;
  height: 300px; /* 需要指定高度 */
}
  1. 使用grid

.parent {
  display: grid;
  place-items: center;
  height: 300px;
}
  1. 使用绝对定位和transform

.center-div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
  1. 使用line-height (单行文本)

.center-div {
  line-height: 300px; /* 等于容器高度 */
  height: 300px;
}

水平和垂直同时居中

  1. flexbox方法

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
  1. grid方法

.parent {
  display: grid;
  place-items: center;
  height: 300px;
}
  1. 绝对定位方法

.parent {
  position: relative;
  height: 300px;
}
.center-div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

示例

<!DOCTYPE html>
<html>
<head>
<style>
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  border: 1px solid #000;
}

.grid-center {
  display: grid;
  place-items: center;
  height: 200px;
  border: 1px solid #000;
  margin-top: 20px;
}

.transform-center {
  position: relative;
  height: 200px;
  border: 1px solid #000;
  margin-top: 20px;
}
.transform-center div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #f0f0f0;
  padding: 10px;
}
</style>
</head>
<body>

<div class="flex-center">
  <div>Flexbox居中</div>
</div>

<div class="grid-center">
  <div>Grid居中</div>
</div>

<div class="transform-center">
  <div>Transform居中</div>
</div>

</body>
</html>