参考资料

  1. Flex布局在动画制作中的应用?
  2. Flexbox 布局有哪些高级用法?
  3. 如何避免 CSS 过渡动画卡顿?
  4. 如何用添加产品图片和描述?
  5. css div阴影效果,
  6. CSS网格详细说明以及案例
  7. 如何提高Flex布局的性能?详细说明
  8. 如何调试Flex布局问题?

css怎么使div居中

CSS使div居中的方法

水平居中

方法1:margin auto

div {
  width: 200px;
  margin: 0 auto;
}

方法2:flexbox

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

垂直居中

方法1:flexbox

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

方法2:绝对定位 + transform

div {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

水平垂直居中

方法1:flexbox

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

方法2:绝对定位 + transform

div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

方法3:grid

.parent {
  display: grid;
  place-items: center;
  height: 300px;
}

完整示例

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

.box {
  width: 100px;
  height: 100px;
  background-color: lightblue;
}
</style>
</head>
<body>

<div class="flex-center">
  <div class="box"></div>
</div>

</body>
</html>