css的十几种水平垂直居中的办法
水平垂直居中方法:
基本样式:
*{ margin: 0;padding: 0;box-sizing: border-box; } body{ margin: 20px; } .box{ width: 200px; height: 200px; border: 1px solid #ccc; } .item{ width: 100px; height: 100px; line-height: 100px; font-size: 12px; background: #ccc; }
基本架构:
<div class="box"> <div class="item"> 内容水平垂直居中 </div> </div>
方法1--table-cell
.box{ display: table-cell; vertical-align: middle; text-align: center; } .box .item{ display: inline-block; }
方法2 - absolute + 负 margin
.box{ position: relative; } .box .item{ position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; }
方法3 - absolute + margin auto
.box{ position: relative; } .box .item{ position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
方法4 - absolute + transform
.box{ position: relative; } .box .item{ position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
方法5 - absolute + calc
.box{ position: relative; } .box .item{ position: absolute; left: calc(50% - 50px); top: calc(50% - 50px); }
方法6 - flex + justify-content + align-items
.box{ display: flex; justify-content: center; align-items: center; }
方法7 - flex + align-self + margin auto
.box{ display: flex; } .box .item{ align-self: center; margin: auto; }
方法8 - grid + align-self + justify-self
.box{ display: grid; } .box .item{ align-self: center; justify-self: center; }
方法9 - writing-mode
.box{ writing-mode: vertical-lr; text-align: center; } .box .item{ writing-mode: horizontal-tb; display: inline-block; margin: 0 calc(50% - 50px); }
方法10 - flex + margin auto
.box{ display: flex; } .box .item{ margin: auto; }
方法11 - grid + justify-items + align-items
.box{ display: grid; justify-items: center; align-items: center; }
本文作者: Jasmine
本文链接: https://www.jianbaizhan.com/article/686
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!