【问题标题】:Content inside a div in a new column on overflow溢出时新列中 div 内的内容
【发布时间】:2019-03-25 08:44:41
【问题描述】:

我找不到让 div 垂直对齐的方法,它会在溢出时换行到第二列...

我有一个固定高度的 div,在里面我有一个动态可变数量的文本,每个文本都包裹在一个固定宽度的 div 中。

我想以垂直对齐方式显示文本。如果没有足够的空间,则应使用第二列。 我尝试使用 float 和 display: inline-block 但元素不在彼此下方。

我觉得有图会更容易理解:

纯 CSS 解决方案将是最好的!

这里是问题的基本 html 代码:

<div class="container" style="height: 70px; background-color: lightblue;">
  <div style="width: 100px;">Alsace</div>
  <div style="width: 100px;">Bretagne</div>
  <div style="width: 100px;">Centre</div>
  <div style="width: 100px;">Lorraine</div>
  <div style="width: 100px;">Picardie</div>
</div>

Context: on the left of the main div, I have a country map with different county which can be selected, when a county is selected I want to display it's name close to the map.这就是为什么我希望文本最靠近左侧。

【问题讨论】:

    标签: html css vertical-alignment


    【解决方案1】:

    更好的方法:

    .container {
        display: flex;
        flex-flow: column wrap;
    }
    

    感谢@Roberrrt



    这可以通过display: flex;来完成

    演示:https://jsfiddle.net/88p36j74/

    您将包装高度设置为 'item height' x 'vertical item count'。

    .container {
      display: flex;
      flex-direction: column;
      align-content: flex-start;
      flex-wrap: wrap;
      height: 250px;/* 5 items x 50px = 250px*/
    }
    .container div {
      height: 50px;
      width: 100px;
      background: red;
    }
    

    【讨论】:

    • .container { display: flex; flex-flow: column wrap } 就够了;)。
    • 谢谢两位。一个非常易于使用的解决方案来解决我的问题!
    【解决方案2】:

    您可以使用column-count1

    .container {
      height: 90px;
      background-color: lightblue;
      column-count: 2;
      column-fill: auto;
    }
    
    .container>div { width: 100px; height: 20px; }
    <div class="container">
      <div>Alsace</div>
      <div>Bretagne</div>
      <div>Centre</div>
      <div>Lorraine</div>
      <div>Picardie</div>
    </div>

    1column-count support

    【讨论】:

    • 这是他不想要的吧?它仍然在右侧对齐 2 列。
    • @Roberrrt - 他确实想要两列,但是它应该是 last(溢出)元素,而不是第二个,因为float 的标准行为。
    • 啊,我明白了,我误解了你的小提琴。
    【解决方案3】:

    你好 =) 您需要将您的 div 包装在另外两个 div 中,代表您想要的列。 这会给出类似的结果:

    <div class="container" style="height: 70px; background-color: lightblue;">
      <div class="column" style="float:left;">
        <div style="width: 100px;">Alsace</div>
        <div style="width: 100px;">Bretagne</div>
        <div style="width: 100px;">Centre</div>
        <div style="width: 100px;">Lorraine</div>
      </div>
      <div class="column" style="float:left;">
        <div style="width: 100px;">Picardie</div>
      </div>
    </div>
    

    类似的东西应该可以工作,但您可能需要在两个 div 上添加固定宽度。

    【讨论】:

    • 这是一个解决方案,但并不理想,因为内容可能会发生巨大变化,更语义化的解决方案是 flexbox。
    猜你喜欢
    • 2012-12-09
    • 1970-01-01
    • 2023-03-24
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 2012-10-14
    • 2014-04-25
    相关资源
    最近更新 更多