1、Line-Height Method
试用:
a、单行文本垂直居中
html:
<div id="parent"> <div id="child">Text here</div> </div>
css:
#child { line-height: 200px; }
b、垂直居中一张图片
HTML:
<div id="parent"> <img src="image.png" alt="" /> </div>
css:
#parent { line-height: 200px; } #parent img { vertical-align: middle; }
2、Table Method
适用:通用
html:
<div id="parent"> <div id="child">Content here</div> </div>
css:
#parent {display: table;} #child { display: table-cell; vertical-align: middle; }
低版本 IE fix bug:
#child { display: inline-block; }
3、Absolute Positioning and Negative Margin
适用:块级元素
html:
<div id="parent"> <div id="child">Content here</div> </div>
css:
#parent {position: relative;} #child { position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -15% 0 0 -25%; }
4、Absolute Positioning and Stretching(即相对定位元素四个方向都是0)
适用:通用,但在IE版本低于7时不能正常工作
html:
<div id="parent"> <div id="child">Content here</div> </div>
css:
#parent {position: relative;} #child { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 50%; height: 30%; margin: auto; }
5、Equal Top and Bottom Padding
适用:通用
html:
<div id="parent"> <div id="child">Content here</div> </div>
css:
#parent { padding: 5% 0; } #child { padding: 10% 0; }
6、Floater Div
适用:通用
HTML:
<div id="parent"> <div id="floater"></div> <div id="child">Content here</div> </div>
css:
#parent {height: 250px;} #floater { float: left; height: 50%; width: 100%; margin-bottom: -50px; } #child { clear: both; height: 100px; }
7.flex
总结:未知宽高垂直居中
1、flex弹性盒子布局
.ele{ /*弹性盒模型*/ display:flex; /*主轴居中对齐*/ justify-content: center; /*侧轴居中对齐*/ align-items: center; }
2、display的table-cell
.box{ /*让元素渲染为表格单元格*/ display:table-cell; /*设置文本水平居中*/ text-align:center; /*设置文本垂直居中*/ vertical-align:middle; }
3、同一行的图片和文字垂直居中 : https://blog.csdn.net/sqc157400661/article/details/72457535
(小图标推荐第三种方法,把图片作为 padding 的背景,使用背景定位中的居中属性)
参考 网站:https://blog.csdn.net/wolinxuebin/article/details/7615098