CSS垂直居中的11种实现方式
注:以下demo都只是针对现代浏览器所做,未兼容低版本的IE以及其它非主流浏览器。
11种实现方式分别如下:
<div id="box"> <div id="child">我是测试DIV</div> </div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; position: relative; } #child { width: 150px; height: 100px; background: orange; position: absolute; top: 50%; margin: -50px 0 0 0; line-height: 100px; }
运行结果如下:
<div id="child"> 我是一串很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文本 </div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; position: relative; } #child { background: #93BC49; position: absolute; top: 50%; transform: translate(0, -50%); }
运行结果如下:
<div id="box"> <div id="child">我也是个测试DIV</div> </div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; position: relative; } #child {
width: 50%; height: 30%; background: pink; position: absolute; top: 50%; margin: -15% 0 0 0; }
运行结果如下:
<div id="box"> <div id="child">呆呆今天退役了(。﹏。)</div> </div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; position: relative; } #child { width: 200px; height: 100px; background: #A1CCFE; position: absolute; top: 0; bottom: 0; margin: auto; line-height: 100px; }
运行结果如下:
<div id="box"> <div id="child">今天西安的霾严重的吓人,刚看了一眼PM2.5是422</div> </div>
css代码:
#box { width: 300px; background: #ddd; padding: 100px 0; } #child { width: 200px; height: 100px; background: #F7A750; line-height: 50px; }
运行结果如下:
<div id="box"> <div id="base"></div> <div id="child">今天写了第一篇博客,希望可以坚持写下去!</div> </div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; } #base { height: 50%; background: #AF9BD3; } #child { height: 100px; background: rgba(131, 224, 245, 0.6); line-height: 50px; margin-top: -50px; }
运行结果如下:
<div id="box">雾霾天气,太久没有打球了</div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; display: flex; align-items: center; }
运行结果如下:
这种方式同样适用于块级元素:
html代码:
<div id="box"> <div id="child"> 程序员怎么才能保护好眼睛? </div> </div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; display: flex; align-items: center; } #child { width: 300px; height: 100px; background: #8194AA; line-height: 100px; }
运行结果如下:
<div id="box"> <div id="child"> 答案当然是多用绿色的背景哈哈 </div> </div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; display: flex; flex-direction: column; justify-content: center; } #child { width: 300px; height: 100px; background: #08BC67; line-height: 100px; }
运行结果如下:
<div id="box"> 我是一段测试文本 </div>
css代码:
#box{ width: 300px; height: 300px; background: #ddd; line-height: 300px; }
运行结果如下:
<div id="box"> <img src="duncan.jpeg"> </div>
css代码:
#box{ width: 300px; height: 300px; background: #ddd; line-height: 300px; } #box img { vertical-align: middle; }
运行结果如下:
<div id="box"> <div id="child">我也是一段测试文本</div> </div>
css代码:
#box { width: 300px; height: 300px; background: #ddd; display: table; } #child { display: table-cell; vertical-align: middle; }
运行结果如下:
这里关于vertical-align啰嗦两句:vertical-align属性只对拥有valign特性的html元素起作用,例如表格元素中的<td><th>等等,而像<div><span>这样的元素是不行的。
valign属性规定单元格中内容的垂直排列方式,语法:<td valign=”value”>,value的可能取值有四种: