html - 将 div 与 flexbox 对齐。 2 个 div 全宽和 2 个 div 在宽度的一半内联

标签 html css flexbox

我正在尝试制作 2 个全宽 div 和 2 个半宽 div 的布局(最后 2 个 div 应该在一行中)。

HTML 如下所示:

<div class="container">
    <div class="box--full">1</div>
    <div class="box--full">2</div>
    <div class="box--half">3</div>
    <div class="box--half">4</div>
</div>

CSS:

* {
    box-sizing: border-box;
}

.container {
    display: flex;
    width: 200px;
    flex-flow: row wrap;
}

[class*="box--"] {
    display: flex;
    margin: .25rem;
    height: 2rem;
    padding: .25rem;
    color: white;
}

.box--full {
    background: red;
    flex: 1 1 100%;
}

.box--half {    
    background: blue;
    flex: 1 1 50%;
}

我想知道为什么最后两个 div 没有可用宽度的一半,为什么它们不在一行中。我想避免为最后 2 个 div 添加包装器。

我发现添加 flex: 0 1 50% 会将所需的宽度应用于最后 2 个 div,但它们仍然不是内联的。

是否可以在不制作额外包装器的情况下使它们内联?

这是 codepen 的链接:http://codepen.io/sunpietro/pen/Mepmam

最佳答案

它们不在同一行,因为它们确实有margin,而margin占用了一点空间,所以你必须降低百分比:

* {
    box-sizing: border-box;
}

.container {
    display: flex;
    width: 200px;
    flex-flow: row wrap;
}

[class*="box--"] {
    display: flex;
    margin: .25rem;
    height: 2rem;
    padding: .25rem;
    color: white;
}

.box--full {
    background: red;
    flex: 1 1 100%;
}

.box--half {    
    background: blue;
    flex: 1 1 30%;
}
<div class="container">
    <div class="box--full">1</div>
    <div class="box--full">2</div>
    <div class="box--half">3</div>
    <div class="box--half">4</div>
</div>

关于html - 将 div 与 flexbox 对齐。 2 个 div 全宽和 2 个 div 在宽度的一半内联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38073281/

相关文章:

css - 为什么card会从parent col溢出

css - flex-grow 什么时候切换到 flex-shrink,反之亦然?

javascript - 如何将 html 标题(工具提示)添加到 leaflet.js 多边形?

html - 右对齐导航栏

javascript - CSS3 slider 过渡效果

html - 溢出没有背景

css - 在 ionic 中更改 ionic View 标题颜色

html - 底部带有元数据的 Css flex div 拉伸(stretch)到相同的高度

css - 在一个 div : one of fixed width and the other of variable width/height 中居中两个 div

php - 如何安全地将登录凭据从 foo.com 传递到 bar.com?