css如何让浮动元素水平居中

对于定宽的非浮动元素我们可以在CSS中用 margin:0 auto 进行水平居中,对于不定宽的浮动元素我们也有一个常用的技巧解决它的水平居中问题。解决水平居中问题有很多种方法,下面先给大家分享一下三种方法,希望能帮助到大家。
方法一:

1、HTML 部分:

?

1 2 3 4 "box" > 我是浮动的
我也是居中的
2、CSS 部分:

?
1 2 3 4 5 6 7 8 9 10 .box{ float:left; position:relative; left:50%; } p{ float:left; position:relative; right:50%; }

这样看来就很简单了吧,父元素和子元素同时左浮动,然后父元素相对左移动50%,再然后子元素相对右移动50%,或者子元素相对左移动-50%也就可以了。如此简单如此神奇。
方法二:
HTML 代码

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 "Content-Type" content= "text/html; charset=utf-8" /> 页面浮动元素的水平居中 - 锐客网 "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; } "wrap clearfix" > "inwrap" >
    "page" >
  • "#" >上一页
  • "#" >1
  • "#" >2
  • "#" >3
  • "#" >4
  • "#" >2
  • "#" >3
  • "#" >2
  • "#" >3
  • "#" >4
  • "#" >5
  • "#" >6
  • "#" >下一页
父元素和子元素同时左浮动,然后父元素相对左移动50%,再然后子元素相对左移动-50%。
方法三:

html代码
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 "http://www.w3.org/1999/xhtml" > "Content-Type" content= "text/html; charset=utf-8" /> 页面元素的水平居中 - 锐客网 "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; } 页面元素的水平居中 浮动方式: "wrap clearfix" > "inwrap" >
    "page" >
  • "#" >上一页
  • "#" >1
  • "#" >2
  • "#" >3
  • "#" >4
  • "#" >2
  • "#" >3
  • "#" >2
  • "#" >3
  • "#" >4
  • "#" >5
  • "#" >6
  • "#" >下一页
【css如何让浮动元素水平居中】这里也可以多套一层的方式设置left:-50%,更合理,也可以避免一些不必要的IE BUG。举一反三,这种float元素居中的方式其实可以延展应用到很多需要浮动元素又居中的情况。

    推荐阅读