参考资料

  1. CSS阴影透明度设置
  2. 动画属性详细说明以及案例
  3. CSS格式化/压缩有哪些
  4. display: flex/inline-flex示例
  5. 属性选择器详细说明以及案例
  6. 哪种布局方式更适合移动端?
  7. Flex布局如何优化页面加载速度?
  8. css中设置div居中

css中div居中

  1. 水平居中方法:

方法1:margin auto

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

方法2:flex布局

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

方法3:grid布局

.parent {
  display: grid;
  place-items: center;
}
  1. 垂直居中方法:

方法1:flex布局

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

方法2:grid布局

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

方法3:绝对定位

.parent {
  position: relative;
  height: 300px;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
  1. 水平垂直同时居中:

方法1:flex布局

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

方法2:grid布局

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

方法3:绝对定位

.parent {
  position: relative;
  height: 300px;
}
.child {
  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 #ccc;
}

.grid-center {
  display: grid;
  place-items: center;
  height: 200px;
  border: 1px solid #ccc;
}

.position-center {
  position: relative;
  height: 200px;
  border: 1px solid #ccc;
}
.position-center div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.box {
  width: 100px;
  height: 50px;
  background: lightblue;
  text-align: center;
  line-height: 50px;
}
</style>
</head>
<body>

<h3>Flex居中</h3>
<div class="flex-center">
  <div class="box">Flex居中</div>
</div>

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

<h3>绝对定位居中</h3>
<div class="position-center">
  <div class="box">绝对定位</div>
</div>

</body>
</html>