theydy / notebook

记录读书笔记 + 知识整理,vuepress 迁移中 https://theydy.github.io/notebook/
0 stars 0 forks source link

CSS 水平垂直居中方式 #5

Open theydy opened 5 years ago

theydy commented 5 years ago

CSS 水平垂直居中方式

CodePan查看效果

方式一:absolute + 负 margin (需要确定 .content 宽高)

.wrapper {
  position: relative;
}
.content {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  margin-top: -50px;
  margin-left: -50px;
}

方式二:absolute + margin: auto(需要确定 .content 宽高)

.wrapper {
  position: relative;
}
.content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100px;
  height: 100px;
  margin: auto;
}

方式三:absolute + transform 未知宽高

.wrapper {
  position: relative;
}
.content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

方式四:flex 未知宽高

.wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}
.content {
}

方式五:table-cell 未知宽高

.wrapper {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.content {
  display: inline-block;
}

方式六:grid 未知宽高

.wrapper {
  display: grid;
  justify-content: center;
  align-content: center;
}
.content {
}