参考资料

  1. css div居中对齐方式
  2. CSS 阴影设置
  3. Flexbox布局有哪些常见的误区?
  4. div居中样式
  5. 动态伪类选择器详细说明以及案例
  6. 如何避免 CSS 过渡动画卡顿?
  7. 元素选择器详细说明以及案例
  8. CSS 阴影边框设置

css样式div居中

CSS居中方法

  1. 水平居中

div {
  margin: 0 auto;
  width: 200px;
}
  1. Flexbox居中

.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;    /* 垂直居中 */
  height: 100vh;
}
  1. Grid居中

.container {
  display: grid;
  place-items: center;
  height: 100vh;
}
  1. 绝对定位居中

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

完整示例

<!DOCTYPE html>
<html>
<head>
<style>
.center-div {
  width: 200px;
  height: 100px;
  background: #ccc;
  
  /* 方法1 */
  margin: 0 auto;
  
  /* 方法2 */
  display: flex;
  justify-content: center;
  align-items: center;
  
  /* 方法3 */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
</head>
<body>

<div class="center-div">居中内容</div>

</body>
</html>