CSS元素居中常用方法

156 阅读1分钟

flex布局水平垂直居中(子元素宽高不确定时)

只需要父级元素设置

   /*flex 布局*/
   display: flex;
   /*实现垂直居中*/
   align-items: center;
   /*实现水平居中*/
   justify-content: center;

未知父元素高度

.parentElement {
  position: relative;
  // 方法1  子元素宽高不确定时
  .childElement {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateY(-50%);
    transform: translateX(-50%);
  }
  
   // 方法2 
  .childElement {
    position: absolute;
    width:100px;
    height:100px;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
  }
  // 方法3
  .childElement {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
  }
}

伪元素:before

.parentElement {
  display: block;
  &:before {
    content: " ";
    display: inline-block;
    vertical-align: middle;
    height: 100%;
  }
  .childElement {
    display: inline-block;
    vertical-align: middle;
  }

display:table-cell

.parentElement {
  display: table;
  .childElement {
    display: table-cell;
    vertical-align: middle;
  }
  .grandsonElement {}
}