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; }