Skip to content

Latest commit

 

History

History
84 lines (66 loc) · 1.12 KB

元素居中.md

File metadata and controls

84 lines (66 loc) · 1.12 KB

table-cell & vertical-align

.wrap {
  width: 600px;
  height: 600px;
  background-color: aliceblue;

  display: table-cell;
  vertical-align: middle;
}

.box {
  width: 100px;
  height: 100px;
  background-color: palegoldenrod;

  margin: 0 auto;
}

margin & position

.wrap {
  width: 600px;
  height: 600px;
  background-color: aliceblue;
  position: relative;
}

.box {
  width: 100px;
  height: 100px;
  background-color: palegreen;

  position: absolute;
  left: 50%;
  top: 50%;
  margin: -50px 0 0 -50px;
}

transform & position

.wrap {
  width: 600px;
  height: 600px;
  background-color: aliceblue;

  position: relative;
}

.box {
  width: 100px;
  height: 100px;
  background-color: palegreen;

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

flex

.wrap {
  width: 600px;
  height: 600px;
  background-color: aliceblue;

  display: flex;
  justify-content: center;
  align-items: center;
}

小结

  • flex 布局最方便, 可是有兼容性问题

  • 已知尺寸可以用 margin & position , 未知尺寸用 table-cell 或者 transform