水平垂直居中的实现

方法一:在已知宽度的情况下,对div改变外边距进行偏移达到效果。
.container {
      width: 500px;
      height: 500px;
      background-color: orange;
      position: relative;
      margin: 0 auto;
}
.content {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 50%;
      left: 50%;
      margin: -50px 0 0 -50px;
}
 
方法二:宽度未知的情况,使用tansform属性。
.container {
      width: 500px;
      height: 500px;
      background-color: orange;
      position: relative;
      margin: 0 auto;
}
.content {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
}
 

 

方法三:使用弹性布局flex。
.container {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 500px;
      height: 500px;
      background-color: orange;
      margin: 0 auto;
}
.content {
      width: 100px;
      height: 100px;
      background-color: red;
}

 

方法四:使用table-cell,需要注意的是content块需要给予inline-block。
.container {
      display: table-cell;
      /* 垂直居中 */
      vertical-align: middle;
      /* 水平居中 */
      text-align: center;
      width: 500px;
      height: 500px;
      background-color: orange;
}
.content {
      display: inline-block;
      width: 100px;
      height: 100px;
      background-color: red;
}
 

 

方法五:使用grid布局
.container {
      display: grid;
      width: 500px;
      height: 500px;
      background-color: orange;
      margin: 0 auto;
}
.content {
      width: 100px;
      height: 100px;
      background-color: red;
      justify-self: center;
      align-self: center;
} 

还有更多,等你探索...

posted @ 2022-08-12 11:44  纯白の约定  阅读(42)  评论(0编辑  收藏  举报