在实际开发过程中,元素居中是常用的布局之一,为此特别整理了几种居中方式:
先看看html文档结构:
<div class="show show1"> <p>1、垂直居中</p> </div>
再看看css样式,因为例子比较多,基础样式都为都为show,后面不再重复了
.show{ width: 200px; height:200px; background: #999; margin: 25px; } .show1{ display: table-cell; vertical-align:middle; text-align: center; }
在浏览器中打开我们可以看到:
这边需要注意:
1、table-cell不感知margin,我在基础样式中添加了margin值,在浏览器开发工具中看不到margin有值。
2、设置float或position会对默认布局造成破坏,可以考虑为之增加一个父div定义float等属性。
html文档结构几乎一样不再重复,直接看css样式:
.show2{ display:flex; justify-content: center; align-items: center; }
相比第一个例子,这边的margin值得以体现。
三、绝对定位和负边距
html文档结构:
<div class="base show show3"> <p>3、绝对定位和负边距</p> </div>
css样式:
.base{ position:relative; } .show3 p{ position:absolute; width:100px; height:50px; top:50%; left:50%; margin-left:-50px; margin-top:-25px; text-align: center; background-color: #007AFF; }
结果如图所示:
四、绝对定位和0
css样式:
.show4 p{ position: absolute; width: 50%; height: 50%; overflow:auto; margin:auto; text-align: center; top: 0; left: 0; bottom: 0; right: 0; background-color: #007AFF; }
结果:
原文:https://www.cnblogs.com/lwxiao/p/10275899.html