【问题标题】:Put content below the shorter column将内容放在较短的列下方
【发布时间】:2015-11-29 12:22:10
【问题描述】:

我有一个“仪表板”类型的布局,其中有两列不同的高度。我有第三个项目,我想添加到最短的列中(见附件截图)。

在第一个示例中,第 1 列较短,因此我们在其下方添加第 3 项,但如果第 2 列较短,则它应该在那里。

我认为我应该使用浮点数,但是它运行不正确。

谁能赐教?

【问题讨论】:

标签: html css layout


【解决方案1】:

这可能与您的预期不太一样,但通过使用 flexbox 列,您可以创建效果。如果您调整 el1 的高度,例如使它成为 150,您将看到形状重新排列。这是我能想到的最好的纯 CSS 解决方案,但如果您需要更大的灵活性,我会推荐 Masonry 插件,正如其他人所说的那样。

    #content {
        width: 400px;
        height: 200px;
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
    }
    
    .box {
        width: 200px;
        flex: none;
        box-sizing: border-box;
        color: white;
        text-align: center;
    }
    
    #el1 {
        height: 50px;
        background-color: green;
    }

    #el2 {
        height: 100px;
        background-color: red;
    }
    
    #el3 {
        height: 100px;
        background-color: yellow;
    }
<div id="content">
    <div class="box" id="el1">1</div>
    <div class="box" id="el2">2</div>
    <div class="box" id="el3">3</div>
</div>

【讨论】:

    【解决方案2】:

    我认为通过纯 CSS 解决方案是不可能的。首先,必须渲染 DOM(渲染 2 个框及其内容),因此您拥有每个框的确切高度。然后你需要计算最短的(Javascript?),然后将第三个框附加到该列。

    综上所述,我认为你需要 JS 和 CSS 的结合

    【讨论】:

    • 可以通过 CSS 实现的。跳出框框思考。
    • 我很想看看您提出的解决方案
    • 多哈。见下文。
    • 正如我在回答中所说,没有纯 CSS 解决方案,您提出的解决方案仍然是 JS 和 CSS 的混合体,所以我不明白“跳出框框思考”的说法。
    【解决方案3】:

    目前这仅使用 CSS 是不可能的,因为 Web 布局通过逐行渲染工作。

    您可以使用像 Masonry 这样的 js 插件或编写自己的实现。

    【讨论】:

    • CSS列布局(或flex with direction = column)有什么作用?
    • @SalmanA 两者都不是这样工作的,它们只是逐列而不是逐行填充(就像中国人的写作方式一样)。除非您限制容器的高度,否则第一列可以无限长并且永远不会换行到第二列。
    【解决方案4】:

    可以左右浮动三个项目:

    #wrapper {
      box-shadow: 0 0 0 1px #CCC;
    }
    /* clearfix */
    #wrapper::after {
      content: "";
      display: block;
      clear: both;
    }
    .item {
      width: calc(50% - 1em);
      margin: .5em;
    }
    /* floats */
    #item-1 {
      float: left;
      background-color: #080;
    }
    #item-2 {
      float: right;
      background-color: #F00;
    }
    #item-3 {
      float: left;
      background-color: #FF0;
    }
    /* demo */
    textarea {
      box-sizing: border-box;
      margin: 1em;
      width: calc(100% - 2em);
      resize: vertical;
    }
    <p>Resize the boxes by dragging the resize handle of the textarea<br> The yellow box will position itself below the shorter of green and red box</p>
    <div id="wrapper">
      <div class="item" id="item-1"><textarea rows="4">1</textarea></div>
      <div class="item" id="item-2"><textarea rows="9">2</textarea></div>
      <div class="item" id="item-3"><textarea rows="4">3</textarea></div>
    </div>

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 2015-11-16
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      相关资源
      最近更新 更多