css中常见的水平垂直居中方式

189 阅读1分钟

前言

前端面试中的高频考点,有空稍微总结一下,希望对大家有帮助

假设html结构为:

<div class="father">
    <div class="son"></div>
  </div>

css结构为:

   * {
      margin: 0;
      padding: 0;
    }
    .father {
      width: 500px;
      height: 300px;
      background-color: skyblue;
    }
    .son {
      width: 100px;
      height: 100px;
      background-color: yellowgreen;
   }

已知宽高

定位+margin:auto

.father {
	position:relative;
}
.son {
	position:absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

定位+负margin

.father {
	position:relative;
}
.son {
	position:absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
}

定位+计算属性calc

.father {
	position:relative;
}
.son {
	position:absolute;
   	top: calc(50% - 50px);
    left: calc(50% - 50px);
}

未知宽高

定位+transform

.father {
	position:relative;
}
.son {
	position:absolute;
   	top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

flex布局

//给父元素设置如下属性:
 .father {
   display: flex;
   justify-content: center;
   align-items: center;
 }

grid布局

.father {
	  display: grid;
      place-items:center;
}