当前位置: 移动技术网 > IT编程>网页制作>CSS > 实现水平垂直居中的五类方法

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

2020年07月14日  | 移动技术网IT编程  | 我要评论

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

基础样式

 <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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网