CSS实现水平垂直居中

这个问题在面试中可能经常被问到,同时CSS的水平居中样式也是项目中需求较大的布局方式。有以下几种常用的方式:

1.已知具体宽高

.father {
  position: relative;
  width: 300px;
  height: 300px;
 }
.child {
  width: 100px; height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -50px 0 0 -50px;
 }

2.采用transform,不限宽高

.father {
  position: relative;
  width: 300px;
  height: 300px;
 }
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%)
 }

3.不限宽高,父元素必须有宽高

.father {
  position: relative;
  width: 300px;
  height: 300px;
 }
.child {
  position: absolute;
  top:0;
  bottom:0;
  left:0;
  right:0
 }

4.更灵活的flex布局

.father {
  display:flex;
  justify-content:center;
  align-items:center;
 }

5.table-cell方式实现

转换成行内元素实现,要求父元素必须有确定的宽高,不能是百分比

.father {
  display:table-cell;
  text-align:center;
  vertical-align: middle;
  width: 300px;
  height: 300px;
 }
.child {
  display: inline-block;
 
 }
posted @ 2021-01-30 11:37  周周的一周  阅读(79)  评论(0)    收藏  举报