Skip to content

元素置中的 5 個方法

1️⃣ Flex

父層設置 display: flex; justify-content: center; align-items: center;

css
/* Type1 parent Flex */
.parent-type1 {
  display: flex;
  justify-content: center;
  align-items: center;
}

2️⃣ relate && absolute

  • 父層 position: relative;
  • 子層 position: absolute;
css
/* Type2 position */
.parent-type2 {
  position: relative;
}
.child-type2 {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -25%;
  margin-top: -25%;
}

3️⃣ translate: 50%

子層 translate 位移。

css
/* Type3 Child set translate 50% */
.child-type3 {
  transform: translate(50%, 50%);
}

4️⃣ grid + place-items:center

css
/* Type4 parent grid */
.parent-type4 {
  display: grid;
  place-items: center;
}

5️⃣ flex + margin: auto

css
/* Type5 flex margin auto */
.parent-type5 {
  display: flex;
}
.child-type5 {
  margin: auto;
}