盒子居中的方法有哪些?

  1. 绝对定位加margin:auto; position: absolute; top:0; right:0; bottom:0; left:0; margin:auto;
  2. 绝对定位+ 负margin position: absolute; top:50%; left:50%; margin:-高/2 -宽/2;
  3. 绝对定位配合calc()计算方法 position: absolute; top:calc(50%-高/2); left:calc(50%-宽/2);
  4. 绝对定位配合+位移 position: absolute; top:50%; left:50%; transform: translate(-50%,-50%)
  5. 弹性盒子布局(flex布局) display: flex; justify-content: center; align-items: center;
  6. grid布局 display: grid; align-self: center; justify-self: center;
  7. 将小div转成inline-block <style> .box{ width: 600px; height: 600px; background-color: blue; text-align: center; /*!*/ line-height: 600px; /*!*/ } .a1{ width: 100px; height: 100px; background-color: black; display: inline-block; /*必写*/ vertical-align: middle; /*必写*/ } </style> <div class="box"> <div class="a1"></div> <span></span> </div>
经验分享 程序员 微信小程序 职场和发展