CSS水平居中的方法有:
1. 通常是套上一层div.wrapper设置width为具体的数值或%比,并设置margin:0 auto
可是若是不但愿给这个div设定宽度怎么办?
2。 套上一层div.wrapper设置display: table, 并设置margin:0 auto, table和div同样可是width不像div那样(div的宽度是水平拉伸100%,table的width由它包裹的内容决定)
3。 套上一层div.wrapper设置display: inline-block, 并设置margin:0 auto , 最后给wrapper的父容器设置text-align:center css
http://stackoverflow.com/questions/4980525/css-center-display-inline-block html
Try this. I added text-align: center to body and display:inline-block to wrap, and then removed your display: table app
body { background: #bbb; text-align: center; } .wrap { background: #aaa; margin: 0 auto; display: inline-block; overflow: hidden; }
If you have a <div> with text-align:center; , then any text inside it will be centered with respect to the width of that container element. inline-block elements are treated as text for this purpose, so they will also be centered. ide
最后上面代码中的overflow:hidden是让当前这个div.wrap不collapse (由于wrap中的元素都是float元素,wrap若是不加overflow:hidden则它的高度将变成0)
this
解决float父容器collapse的方法共有4种:
1) 设置父容器 的overflow: hidden(或overflow)缺点是若是父容器中有下拉菜单什么的超出容器的部分会被遮挡并且overflow这个属性用来清除collapse看起来实在有点另类
2) 设置父容器的float: left, 缺点是父窗口自身变成float可能在位置上有所偏移
3) 在最后一个float元素以后而且在父容器闭合以前的地方加上<div class="clear"></div>并设置.clear {clear:both}缺点是这段额外的html代码看起来有点脏。
4) 给float父容器增长一个class,名为grouping或clearfix之类的。并设定这个类的样式以下: spa
.grouping:before, .grouping:after{ content: ' ', display: table } .grouping:after{ clear: both, }
这个.grouping:before和.grouping:after不是在.grouping元素的前面和后面加上content而是.grouping内部加上content
(至关于使用了$('.grouping').prepend(content)和$('.grouping').append(content):
仍是看这里吧:https://css-tricks.com/all-about-floats/写得更准确和清楚,它和我在mastering CSS看到的清除collapse的方法略有不一样,以下:
code
.clearfix:after { content: "."; visibility: hidden; display: block; height: 0; clear: both; }