Center parent div with floating children [duplicate]

送分小仙女□ 提交于 2019-12-11 08:59:25

问题


I am trying to create a responsive grid. I have a 'parent' div which contains floating children. Depending on the page width a variable number of children is shown per 'row'. The children should be centered.

To get the 'parent' div to fit the children I set display:table on the parent div.

Please see the following fiddle:

http://jsfiddle.net/dwjbosman/cXuQ6/5/

css:

.page {
    background: #a00;
    width:700px;
    margin: 20px;
}
.Parent {
    background: #ccc;
    border: 1px solid black;
    display: table;
    margin-left: auto;
    margin-right:auto;
}
.Child {
    float: left;
    width: 150px;
    height: 50px;
    background:red;
    margin: 5px;
}
.br {
    clear: both;
}

html:

<div class='page'>O1
<div class="Parent">
    <div class="Child">a</div>
    <div class="Child">b</div>
    <div class="Child">c</div>
    <div class="Child">d</div>
</div>

Example O1 works as expected. However I want it to work with more floating children.

Example O2: works if I manually insert a clear: both after one row of children. This of course breaks the responsiveness of the layout.

If I leave out the 'clear' it no longer works and the result is example O3. The parent div becomes too wide and the children are no longer centered.

Is there a way to get the example O2 behavior while retaining responsive behavior?


回答1:


Using CSS3, you can clear every 4th .Child, starting at #5:

div.Child:nth-child(4n+5){
    clear: both;
    background-color: #ddf;
}

Browser support isn't terrible: https://developer.mozilla.org/en-US/docs/CSS/:nth-child#Browser_compatibility

I forked your fiddle: http://jsfiddle.net/ghodmode/y8g2V/



来源:https://stackoverflow.com/questions/16134562/center-parent-div-with-floating-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!