方法一:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>页面元素的水平居中</title> <style type="text/css"> * { margin:0; padding:0; list-style:none; font-size:14px; font-family:Tahoma, Geneva, sans-serif; } .clearfix:after { content:""; height:0; visibility:hidden; display:block; clear:both; } .clearfix { zoom:1; } a{ text-decoration:none;} h1{ text-align:center; padding:10px; font-size:20px; margin:30px 0;} /** 包装器,relative */ .wrap { margin:20px auto; padding:10px 0; background:orange; overflow:hidden; position:relative; } /** relative left 50% */ .page { float:left; position:relative; left:50%; } /** relative right 50% */ .page li { float:left; position:relative; right:50%; overflow:hidden; margin:0 5px; } </style> </head> <body> <h1>页面元素的水平居中</h1> <h2>浮动方式:</h2> <div class="wrap clearfix"> <ul class="page"> <li> <a href="#">上一页</a> </li> <li> <a href="#">1</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">4</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">4</a> </li> <li> <a href="#">5</a> </li> <li> <a href="#">6</a> </li> <li> <a href="#">下一页</a> </li> </ul> </div> </body> </html>
这里主要用到position:relative配合left:50%的技巧,兼容各浏览器,需要注意的是IE7下需要设置overflow:hidden;来解决无法设置子元素宽度的BUG。
方法二:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>页面元素的水平居中</title> <style type="text/css"> * { margin:0; padding:0; list-style:none; font-size:14px; } .clearfix:after { content:""; height:0; visibility:hidden; display:block; clear:both; } .clearfix { zoom:1; } a{ text-decoration:none;} h1{ text-align:center; padding:10px; font-size:20px; margin:30px 0;} .wrap { margin:20px auto; padding:10px 0; background:orange; overflow:hidden; position:relative; } .inwrap{ float:left; position:relative; left:50%;} .page { float:left; position:relative; left:-50%; } .page li { float:left;margin:0 5px; } .page li a { display:block; padding:2px 9px; background:white; border:1px solid red; float:left;} </style> </head> <body> <h1>页面元素的水平居中</h1> <h2>浮动方式:</h2> <div class="wrap clearfix"> <div class="inwrap"> <ul class="page"> <li> <a href="#">上一页</a> </li> <li> <a href="#">1</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">4</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">4</a> </li> <li> <a href="#">5</a> </li> <li> <a href="#">6</a> </li> <li> <a href="#">下一页</a> </li> </ul> </div> </div> </body> </html>
这里也可以多套一层的方式设置left:-50%,更合理,也可以避免一些不必要的IE BUG。举一反三,这种float元素居中的方式其实可以延展应用到很多需要浮动元素又居中的情况。