【问题标题】:achieving equal height columns with flexbox使用 flexbox 实现等高列
【发布时间】:2016-03-08 18:14:11
【问题描述】:

我正在尝试构建一个具有两个独立内容组的布局:一个在左侧和一个右侧,目前具有固定宽度 (20%/80%)。在每一侧,我都尝试使用 flexbox 来排列内容:左侧面板使用flex-direction: column,右侧面板使用flex-direction: row wrap。每一面的内容数量可以是灵活的。内容较少的面板应与另一侧“更高”的高度相匹配。

到目前为止,我能够实现基本布局,如jsfiddle所示。但是,我的问题是我无法使“较短”面板填充高度,即使我将高度设置为 100%。在给定的示例中,左侧面板的“C”div 和右侧面板的“Box7”div 之间有一个空白区域。 html/css 代码如下所示。

我该如何解决这个问题,或者有更好更简单的布局解决方案吗?任何帮助将不胜感激。

HTML

<div class='top'>
    <div class='left'>
        <div class='litem'>A</div>
        <div class='litem'>B</div>
        <div class='litem'>C</div>
    </div>
    <div class='right'>
        <div class='ritem'>Box 1</div>
        <div class='ritem'>Box 2</div>
        <div class='ritem'>Box 3</div>
        <div class='ritem'>Box 4</div>
        <div class='ritem'>Box 5</div>
        <div class='ritem'>Box 6</div>
        <div class='ritem'>Box 7</div>
    </div>
</div>

CSS

* { outline: 1px solid Grey; }

html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    background-color: Cornsilk;
}

.top {
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: row;
    width: 100%;
    height: 100%;
}

.left {
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    width: 20%;
    height: 100%;
}

.right {
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    width: 80%;
    height: 100%;
}

.litem, .ritem {
    margin: 0;
    padding: 0;
}

.litem { height: 50%; }
.ritem { height: 50%; width: 33.3%;}

.litem:nth-child(1) { background-color: Cyan; }
.litem:nth-child(2) { background-color: DarkCyan; }
.litem:nth-child(3) { background-color: DarkSeaGreen; }

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    当您将height: 100% 应用于htmlbody 时,您将子元素的增长限制为屏幕的100%。

    在您的代码中,您的.left 弹性项目确实按照指定延伸到height: 100%。在.left 周围添加边框以作说明:DEMO

    如果您删除所有固定高度,您将启用 flex 容器以拉伸所有 flex 项,默认设置为:align-items: stretch(创建等高列的设置)。 DEMO

    当您将 flex: 1 添加到 .left 弹性项目 (.litem) 时,它们会平均分配容器中的所有可用空间。 DEMO.

    简而言之,当您使用 height 属性时,您覆盖 align-items: stretch,即等高列的 flex 设置。

    【讨论】:

    • 感谢您的精彩提示!不过有一件事,现在我注意到我无法再控制单个内容框的高度。换句话说,.litem, .ritem {height: 50%} 不起作用,将所有内容框压缩到顶部。对这部分有什么建议吗?
    • 您在.litem 框中使用的任何类型的height 值(例如px、em 或vh -- 但不是百分比)都可以使用。这是高度为 200 像素的盒子。保持等高列:jsfiddle.net/31v8jzu5/15
    • 哦,我明白了。然后,我似乎无法自动控制框高度以适应屏幕,以便不显示滚动条?
    • 是的。它工作得非常好。我从你的 cmets 身上学到了很多东西。非常感谢您的帮助! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2016-09-26
    • 2015-01-21
    • 2017-02-28
    相关资源
    最近更新 更多