
拖延症太强,每次想写点东西的时候总是会想着明天写,今天强行克服了,总算是动工了,好吧,我的第一篇技术博客。
说真的css这玩意儿,很多人认为写写就行了,但在我看来这东西的复杂程度不下于js,写好真的是很难很难,各种布局都有不同的写法,写这个的原因是把常写的东西总结一下,希望给大家参考参考,同时也是对我自己的一个学习总结吧,见识不足,还请谅解。
html统一样式
1 2 3
| <div class="text"> <span class="pox"></span> </div>
|
知道高度
1.绝对定位absolute
1 2 3 4 5 6 7 8 9 10 11 12 13
| .text1{ position: relative; height: 400px; } .pox1{ line-height: 30px; position: absolute; top: 50%; margin-top: -30px; }
|

2.单行文本,这个简单
1 2 3 4 5
| .text4{ line-height:400px; height: 400px; }
|

不知道高度
1.table-cell,把div作为一个表格单元格使用,单元格垂直居中?so easy,用vertical-align: middle.
1 2 3 4 5 6 7 8 9 10 11
| 父标签 .text2{ display: table-cell; vertical-align: middle; height: 400px; } 子标签 .pox2{ display: inline-block; }
|

2.table,原理同上
1 2 3 4 5 6 7 8 9 10 11
| 父标签 .text3{ display: table; height: 400px; } 子标签 .pox3{ display: table-cell; vertical-align: middle; }
|

3.妙用:after占位居中,让:after占据全部高度,然后使用vertical-align:middle与:after竖直居中对齐,由于:after宽为0,看不见,就表现为pox5垂直居中了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 父标签 .text5{ height: 400px; } .text5:after{ content:''; width:0; height:100%; display:inline-block; vertical-align:middle; } 子标签 .pox5{ vertical-align:middle; display:inline-block; }
|

4.display:flex,这玩儿说起来就多了,弹性盒子布局,布局爽到飞起,就是兼容性有点问题,不过加上-webkit-后能适应绝大部分游览器
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 父标签 .text6{ display: -webkit-flex; display: flex; height: 400px; -webkit-align-items: center; align-items: center; } 子标签 .pox6{ -webkit-flex: 1; flex: 1; }
|

5.display:-webkit-box,这个是flex的旧版本,同上
1 2 3 4 5 6
| 父标签 .text7{ display: -webkit-box; -webkit-box-align:center; height: 400px; }
|

1 2 3 4 5 6 7 8 9 10 11 12 13
| 父标签 .text8{ position: relative; height: 400px; } 字标签 .pox8{ position: absolute; top: 50%; transform: translateY(-50%); left: 0; }
|

css的妙处就是可以用很多种方法实现同一个效果,本文代码地址:链接