如题,用html,css如何实现垂直居中。水平居中我们知道最简便的方法就是margin:auto,但是margin只是相对宽度有效。
即垂直居中的元素高度已知,这个比较简单,也不需要额外的辅助元素。
<!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>
运行代码
居中元素高度可变,这个需要额外的一个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. <br /> i'm Mr. Middle. <br /> i'm Mr. Middle. <br /> </div> </div> </body> </html>
posted on 2010-03-18 09:16 nozer0 阅读(384) 评论(0) 编辑 收藏 举报
Powered by: 博客园 Copyright © 2024 nozer0 Powered by .NET 8.0 on Kubernetes