水平垂直居中

水平

  1. text-align: center
  2. margin: 0 auto
  3. 当子元素包含float
.parent {
  width: fit-content;
  margin: 0 auto;
}
  1. 两种flex
.child  {
  display: flex;
  justify-content: center;
}
.parent {
  display: box;
  box-pack: center;
}
  1. transform
.child {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0)
}
  1. absolute
.child {
  position: absolute;
  width: 50px;
  left: 50%;
  margin-left: -0.5* 50px;
}
.child {
  position: absolute;
  width: 50px;
  left: 0;
  right: 0;
  margin: 0 auto;
}

垂直

  1. line-height
  2. 基线对齐
.parent::after, .child {
  display: inline-block;
  vertical-align: middle
}
.parent::after {
  content: '';
  height: 100%;
}
.parent{
  display: table;
}
.child{
  display: table-cell;
  vertical-align: middle;
}
  1. IE8 IE9不支持
.parent {
  display: flex;
  align-items: center
}
.parent {
  display: box;
  box-orient: vertical;
  box-pack: center
}
.child {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
}
.child {
  position: absolute;
  top: 50%;
  height: 50px;
  margin-top: -0.5* 50px
}
.child {
  position: absolute;
  height: 50px;
  top: 0;
  bottom: 0;
  margin: auto 0;
}

你可能感兴趣的:(水平垂直居中)