本文转载于:猿2048网站关于令元素垂直居中的总结php
最近在回顾以前的笔记,发现对元素垂直居中的方法都有点一头雾水了,上网查看了一下资料,写着总结css
要令一个元素内的文字对齐,可将元素的行高(line-height)设置与元素高度一致,主要原理是利用基线的调整
代码以下html
<div class="demo"> <span>These</span> <span>elements</span> <span>will be</span> <span>centered vertically</span> </div>
.demo { backgroundcolor:black; padding: 50px; } .demo span { backgroundcolor:gray; color: white; padding: 30px 0; }
固然也能够模拟表格的行为来达到效果布局
<div id='out'> <span>hehe</span> </div>
#out{ width:200px; height:200px; background:blue; display:table; } span{ display:tablecell; verticalalign:middle; }
模拟表格行为以后对内部元素设置verticalalign:middle.能够达到居中的效果flex
先把HTML布局写出来网站
<div id='out'> <div id='inn'></div> </div>
我的比较经常使用的三种方法spa
#out{ position:relative; } #inn{ position:absolute; top:50%; transform:translateY(50%); /*这里的transform属性的translate值,设置的50%是相对于内部元素自身宽高而言*/ }
这里的主要过程是先用绝对定位将内部块级元素的左上角定位到外壳元素的中部,在利用transform将其高度再“掰”回来一半(这里的一半是指内部元素高度的一半),这样就能够恰好使内部元素的中点定位在外壳元素的中点上(也就是取代了原来因为绝对定位后左上角的那个定位点)code
#out{ width:200px; height:200px; background:blue; display:flex; /*flex布局*/ justify-content: center; /*水平居中*/ align-items: center; /*垂直居中*/ }
这里我将水平也居中了,弹性布局须要注意的一点就是在外部父元素上设置 display:flex; 使其内部元素造成布局,因此对内部元素进行设置的话只会对更深层次的元素有效,不是对其自己有效。
还看到有人这样用弹性布局orm
#out{ width:200px; height:200px; background:blue; display:flex; } #inn{ width:100px; height:100px; background:green; margin:auto; }
一样是在外部父元素设置布局,而再对内部元素的margin值设置,这样的话能够利用margin值对其进行想要的定位,不必定是中间(这种定位效果利用绝对定位也能够达到)htm
#out{ width:200px; height:200px; background:blue; position:relative; } #inn{ width:100px; height:100px; background:green; position:absolute; margin:auto; top:0;bottom:0;left:0;right:0; }
这一个感受比较高玩,原理在网上看了好像是利用了CSS的溢出,可是都讲得不是很清楚,有知道的朋友能够给我留言啊!!!