DamomHd / interview-question

整理各大厂面试题
1 stars 0 forks source link

实现水平垂直居中的N种方式 #21

Open DamomHd opened 3 years ago

DamomHd commented 3 years ago
<div class="container">
  <div class="content"></div>
</div>
.container{
      width:500px;
      height:500px;
      background-color:#999;
}
.content{
     width:200px;
     height:200px;
     background-color:#333;
}
DamomHd commented 3 years ago

absolute + margin

.container{
  position:relative;
}
.content{
  position: absolute;
  top: 0;
  bottom:0;
  right:0;
  left: 0;
  margin:auto;
}
DamomHd commented 3 years ago

absolute + transform

.container {
    position: relative;
}
.content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
DamomHd commented 3 years ago

flex

.container {
    display: flex;
    justify-content: center;
    align-items: center;
}
.content {
    text-align: center;
}
DamomHd commented 3 years ago

grid

.container {
    display: grid;
    justify-items: center;
    align-items: center;
}
.content {
    text-align: center;
}
DamomHd commented 3 years ago

css-table

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