【问题标题】:Make child divs expand to fill parent div's width使子 div 扩展以填充父 div 的宽度
【发布时间】:2013-07-19 09:19:06
【问题描述】:

所以我在一个 div 中有三个 div。

<div class="parent">
<div class="child> Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
</div>

我希望子 div 填充父级的宽度(子级的组合宽度应该是父级)。但是,这没有发生,我功亏一篑。我认为这是因为子 div 根据其内容设置宽度。

如何实现我想要的?

CSS-

.child {
    background: white;
    color: #a7a9ac;
    cursor: pointer;
    font-size: 15px;
    border-right: 1px;
    border-top: 0;
    border-bottom: 0;
    border-left: 0;
    border-style: solid;
    border-color: @faded-grey;
    padding-right: 10px;
    margin: 0 auto;
    height: 100%;
}

.parent {
    border-top: 1px;
    border-left: 0;
    border-bottom: 1;
    border-style: solid;
    border-color: @faded-grey;
    border-right: 0;
    width: 100%;
    margin-right: 0px;
    height: 80px;

}

【问题讨论】:

  • 你能把你正在使用的css贴出来吗?
  • 方法有很多,但要看你想要什么。在内容确定其宽度后,您是否希望 last 子 div 填充任何剩余空间?还是希望它们均匀分布,通过width: 33%@?
  • 设置 CSS,尝试了 width:33%,但它把 div 一个一个放在另一个上面

标签: html css


【解决方案1】:

如果你知道总会有三个孩子,你可以简单地使用:

.parent > .child {
    float: left;
    width: 33%;
}

.parent {
    overflow: auto; /*or whatever float wrapping technique you want to use*/
}

如果您不知道有多少孩子,则需要使用 CSS 表格、flexbox,或者可能将 inline-blocks 与 text-align: justify 结合使用。

【讨论】:

    【解决方案2】:

    您可以将这三个属性添加到.child CSS 规则中:

    width:33%;
    float:left;    
    box-sizing: border-box;
    

    最后一行确保在您向框添加边框、内边距和边距时它也能正常工作。

    ONLINE DEMO

    Ps:不直接相关,但在边框底部也有错误,在上面的小提琴中更正。使用非 0 值时需要指定单位:

        border-bottom:1px;
    

    【讨论】:

    • 酱汁真棒!在适当尊重其他答案的情况下,我认为这是最好的答案。
    • 使中间的宽度为 34%,否则只能填满容器的 99%。
    【解决方案3】:

    我需要让我的解决方案适应元素数量的变化,以便它们完全响应。

    我发现了一个有趣的解决方案。它本质上像一张桌子一样显示。每个元素共享可用宽度,这也适用于图像非常好: http://jsfiddle.net/8Qa72/6/

    .table {
        display: table;
        width: 400px;
    }
    
    .table .row {
        display: table-row;
    }
    
    .table .row .cell {
        display: table-cell;
        padding: 5px;
    }
    
    .table .row .cell .contents {
        background: #444;
        width: 100%;
        height: 75px;
    }
    

    【讨论】:

    • 另一个有趣的解决方案是使用display: inline-block 试试看,它有时可以挽救生命;-)
    • 怎么样?它不会在子级之间平均分配父级的可用宽度。你能在 JSFiddle 中给我看吗?
    • 没错,如果你想要类似的东西,你必须为每个孩子指定父 div 的百分比我尝试了“动态”方法和“固定”方法jsfiddle.net/dBeNv/40
    【解决方案4】:

    我很惊讶没有人建议使用 flex 的 css3 解决方案:

    .parent {
      display: flex;
      flex-wrap: wrap;
    }
    
    .child {
      flex: 1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2015-09-21
      • 2017-08-06
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      相关资源
      最近更新 更多