css之实现水平垂直居中的几种方法总结

108 阅读1分钟

实现水平居中的方法

html:

<div class="parent">
 <div class="child">Hello</div>
</div>

公用css:

.parent,
.child {
   padding: 10px;
}
.parent {
   background: #f2f2f2;
}
.child {
   background: #ccc;
}

方法一:inline-bock + text-align

.parent {
   text-align: center;
}
.child {
   display: inline-block;
}   

方法二:absolute + transform

.parent {
   position: relative;
}
.child {
   position: absolute;
   left: 50%;
   transform: translateX(-50%);
}

方法三:flex + justify-content/margin

.parent {
   display: flex;
   justify-content: center;
}
.parent {
   display: flex;
}
.child {
   margin: 0 auto;
}

实现垂直居中的方法

html:

<div class="parent">
 <div class="child">Hello</div>
</div>

公用css:

.parent,
.child {
   padding: 10px;
}
.parent {
   background: #f2f2f2;
   height:100px;
}
.child {
   background: #ccc;
}

方法一: table-cell + vertical-align

.parent {
  display: table-cell;
  vertical-align: middle;
}

方法二:absolute + transform

.parent {
   position: relative;
}
.child {
   position: absolute;
   top: 50%;
   transform: translateY(-50%);
}

方法三:flex + align-items

.parent {
  display: flex;
  align-items: center;
}

实现水平垂直居中的方法

html:

<div class="parent">
 <div class="child">Hello</div>
</div>

公用css:

.parent,
.child {
   padding: 10px;
}
.parent {
   background: #f2f2f2;
   height:100px;
   width:100px;
}
.child {
   background: #ccc;
}

方法一:inline-bock + text-align + table-cell + vertical-align

.parent {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}
.child {
   display: inline-block;
}

方法二:absolute + transform

.parent {
   position: relative;
}
.child {
   position: absolute;
   top: 50%;
   transform: translateY(-50%,-50%);
}

方法三:flex + align-items + justify-content

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