【问题标题】:Center parent div with floating children [duplicate]带有浮动子项的中心父 div [重复]
【发布时间】:2013-04-14 14:44:34
【问题描述】:

我正在尝试创建一个响应式网格。我有一个包含浮动子级的“父级”div。根据页面宽度,每个“行”显示可变数量的子项。孩子们应该居中。

为了让“父”div 适合我在父 div 上设置 display:table 的子元素。

请看下面的小提琴:

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>

示例 O1 按预期工作。但是我希望它可以与更多浮动的孩子一起使用。

示例 O2:如果我在一行孩子之后手动插入 clear: both 则有效。这当然会破坏布局的响应能力。

如果我省略了“清除”,它将不再起作用,结果是示例 O3。父 div 变得太宽,孩子不再居中。

有没有办法在保留响应行为的同时获取示例 O2 行为?

【问题讨论】:

标签: html css grid responsive-design centering


【解决方案1】:

使用 CSS3,您可以每 4 次清除一次 .Child,从 #5 开始:

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

浏览器支持还不错:https://developer.mozilla.org/en-US/docs/CSS/:nth-child#Browser_compatibility

我叉了你的小提琴:http://jsfiddle.net/ghodmode/y8g2V/

【讨论】:

  • 在您的解决方案中,我仍然需要指定每行的子项数。我正在寻找一种解决方案,其中每行的子项数由浏览器确定。
猜你喜欢
  • 2017-12-04
  • 1970-01-01
  • 2019-01-18
  • 2011-11-29
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多