欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

实现水平垂直居中的五类方法

程序员文章站 2022-07-06 16:33:04
实现水平垂直居中的五类方法基础样式 基本骨架<...

实现水平垂直居中的 五类 方法

基础样式

 <style>
      .big {
        width: 200px;
        height: 200px;
        border: 2px solid blue;
      }
      .small {
        width: 50px;
        height: 50px;
        background-color: pink;
      }
 </style>

基本骨架

<div class="big outSideDiv">
      <div class="small innerDiv"></div>
</div>

实现水平垂直居中的五类方法
第一类 定位的方法+偏移

 /* 方法一 */
      .outSideDiv {
        position: relative;
      }
      .innerDiv {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
  /* 方法二 */
     .outSideDiv {
        position: relative;
      }
      .innerDiv {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
      } 
 /* 方法三 */
    .outSideDiv {
        position: relative;
      }
      .innerDiv {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -25px;
        margin-top: -25px;
      } 

第二类方法 css的弹性布局flex

 /* 方法一 */
    .outSideDiv {
        display: flex;
        justify-content: center;
        align-items: center;
      } 
 /* 方法二 */
      .outSideDiv {
        display: flex;
      }
      .innerDiv {
        margin: auto;
      }

第三类 css的grid方法;

 /* 方法一 */
      .outSideDiv {
        display: grid;
      }
      .innerDiv {
        justify-self: center;
        align-self: center;
      } 
  /* 方法二 */
      .outSideDiv {
        display: grid;
      }
      .innerDiv {
        margin: auto;
      } 

第四类对齐方法,用到css的calc()方法

 .innerDiv {
        margin: 0 auto;
        margin-top: calc(50% - 25px);
      } 

第五类 利用表格的属性

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

有更好的方法,希望告知,感谢!

本文地址:https://blog.csdn.net/weixin_45695727/article/details/107326946