css 实现文字垂直居中 文字,垂直居中

css 实现文字垂直居中 文字,垂直居中

如题,用html,css如何实现垂直居中。水平居中我们知道最简便的方法就是margin:auto,但是margin只是相对宽度有效。

关键词:

分两种情况:

fix height:

即垂直居中的元素高度已知,这个比较简单,也不需要额外的辅助元素。

<!DOCTYPE HTML> <html> <head> <meta http-equiv=”content-type” content=”text/html; charset=utf-8″ /> <meta http-equiv=”cache-control” content=”no-cache” /> <style> <!– html, body { height: 100%; margin: 0; padding: 0; } body { position: relative; } #div { background: blue; color: #fff; position: absolute; top: 50%; left: 50%; height: 240px; width: 240px; margin: -120px 0 0 -120px; } –></style> </head> <body> <div id=”div”> i’m Mr. Middle. </div> </body> </html>

提示:您可以先修改部分代码再运行

variable height:

居中元素高度可变,,这个需要额外的一个wrapper元素,用table-cell的方式来模拟表格的居中实现,当然,早期的ie又是另一招,具体可见代码。

<!DOCTYPE HTML> <html> <head> <meta http-equiv=”content-type” content=”text/html; charset=utf-8″ /> <meta http-equiv=”cache-control” content=”no-cache” /> <style> <!– html, body { height: 100%; margin: 0 auto; padding: 0; } body { position: relative; display: table; } #wrapper { display: table-cell; vertical-align: middle; text-align: middle; } #div { background: blue; color: #fff; } * html #wrapper, *+html #wrapper { position: absolute; top: 50%; } * html #div, *+html #div { position: relative; top: -50%; } –></style> </head> <body> <div id=”wrapper”> <div id=”div”> i’m Mr. Middle. i’m Mr. Middle. i’m Mr. Middle. </div> </div> </body> </html>

提示:您可以先修改部分代码再运行

css 实现文字垂直居中 文字,垂直居中

相关文章:

你感兴趣的文章:

标签云: