css居中

208 阅读1分钟

写在最前面

  • 本文主要讨论垂直居中,水平居中不做过多讨论。
  • 实际开发中,常用的有水平居中有①②,垂直居中有①②
  • 使用绝对定位的,父元素要设置相对定位(position:relative)。

一、水平居中

  1. 行内元素:直接给父元素设置text-align:center;
.parent{
    text-align:center;
}
  1. 块级元素:该元素设置margin:0 auto;
.son{
    margin:0 auto;
}
  1. flex布局 (Webkit 内核的浏览器,加上-webkit前缀)
.parent{
    display:flex;
    justify-content: center;
}
  1. 使用绝对定位,宽度固定
.son{
    position: absolute;
    width: 100px;
    left: 50%;
    margin-left: -50px;
    //或者
    //position: absolute;
    //width: 100px;
    //left:0;
    //right:0;
    //margin:0 auto;
    
}
  1. 使用绝对定位、css3,宽度不固定
.son{
    position: absolute;
    left: 50%;
    transform: translate(-50%,0);
}

二、垂直居中

  1. 单行文本,设置line-height等于父元素高度即可。
  2. 使用绝对定位,高度固定
.son{
    position: absolute;
    height: 100px;
    top: 50%;
    margin-top: -50px;
    //或者
    //position: absolute;
    //height: 100px;
    //top:0;
    //bottom:0;
    //margin:auto 0;
    
}
  1. 使用绝对定位、css3,高度不固定
.son{
    position: absolute;
    top: 50%;
    transform: translate(0,-50%);
}
  1. flex布局 (Webkit 内核的浏览器,加上-webkit前缀)
.parent{
    display:flex;
    align-items:center;
}
  1. table实现
.parent{
    display:table;
}
.son{
    display:table-cell;
    vertical-align:middle;
}

6.伪类实现(行内块元素)

.parent::after, .son{
    display:inline-block;
    vertical-align:middle;
}
.parent::after{
    content:'';
    height:100%;
}

参考链接