css实现水平垂直居中的几种方式

以下:wp为父级,box 为子级

.wp {
   position: relative;
}
/* 如子元素为固定宽高,设置宽高分别为100px */
.box{
   width: 100px;
   height: 100px;
}

仅居中元素定宽高适用

  • absolute + 负margin
.box {
    position: absolute;;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}
  • absolute + margin auto
.box {
    position: absolute;;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
  • absolute + calc
.box {
    position: absolute;;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
}

居中元素不定宽高

  • absolute + transform
.box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
  • lineheight
.wp {
    line-height: 300px;
    text-align: center;
    font-size: 0px;
}
.box {
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    line-height: initial;
    text-align: left; /* 修正文字 */
}
  • writing-mode(改变文字的显示方向)
123123
/* 定位代码 */ .wp { writing-mode: vertical-lr; text-align: center; } .wp-inner { writing-mode: horizontal-tb; display: inline-block; text-align: center; width: 100%; } .box { display: inline-block; margin: auto; text-align: left; }
  • table(方法就是代码太冗余,这里就不做介绍了)
  • css-table
.wp {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.box {
    display: inline-block;
}
  • flex
.wp {
    display: flex;
    justify-content: center;
    align-items: center;
}
  • grid(兼容性不如flex好)
.wp {
    display: grid;
}
.box {
    align-self: center;
    justify-self: center;
}

你可能感兴趣的:(css实现水平垂直居中的几种方式)