Words etch cherished moments.
OG

让盒子居中的几种方法

1,247 words, 3 min read
2018/08/24 AM
806 views

#宽高固定的情况下

          
  • 1
  • 2
  • 3
<div class="wrap"> <div class="item"></div> </div>

第一种:利用绝对定位,topleft 50%,然后再利用margin-leftmargin-top把盒子移动其宽高的一半实现

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
.wrap { position: relative; width: 200px; height: 200px; } .item { position: absolute; top: 50%; width: 100px; height: 100px; margin-top: -50px;

第二种:利用绝对定位top,right,bottom,left设置为 0,然后再利用margin:auto实现

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
.wrap { position: relative; width: 200px; height: 200px; } .item { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto;

第三种:宽高已知,利用绝对定位,top,left 设置 50%,然后再利用 CSS3 属性transform:translate(-50%,-50%)实现

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
.wrap { position: relative; width: 200px; height: 200px; } .item { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);

第四种:利用弹性盒模型,主轴交叉轴居中实现

          
  • 1
  • 2
  • 3
  • 4
  • 5
.wrap { display: flex; justify-content: center; align-items: center; }

第五种:利用grid实现

          
  • 1
  • 2
  • 3
  • 4
  • 5
.wrap { display: grid; justify-content: center; align-items: center; }

第六种:利用 table 实现

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
.wrap { display: table-cell; vertical-align: middle; } .item { margin: auto; }
Published at2018/08/24 AMinCode
#CSS
Creative Commons BY-NC 4.0
https://zhangwurui.cn/article/21
0/0comments
Guest
Start the discussion...
Be the first to comment