css如何让浮动元素水平居中
css如何让浮动元素水平居中方式一
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>页面浮动元素的水平居中</title>
<style type="text/css">
.clearfix:after { content:""; height:0; visibility:hidden; display:block; clear:both; }
.clearfix { zoom:1; }
.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>
<li 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>
</li>
</body>
</html>
这里主要用到position:relative配合left:50%的技巧,父元素和子元素同时左浮动,然后父元素相对左移动50%,再然后子元素相对右移动50%。
方式二
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>页面浮动元素的水平居中</title>
<style type="text/css">
.clearfix:after { content:""; height:0; visibility:hidden; display:block; clear:both; }
.clearfix { zoom:1; }
.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>
<li class="wrap clearfix">
<li 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>
</li>
</li>
</body>
</html>
父元素和子元