【问题标题】:How to set width based on content length using flex [duplicate]如何使用 flex 根据内容长度设置宽度 [重复]
【发布时间】:2018-01-22 17:24:54
【问题描述】:

我正在尝试根据内容设置每个项目的宽度,但到目前为止我将宽度一直设置为可用空间。 flex: 0 0 auto 似乎不起作用。我做错了什么?

目标是根据内容大小设置宽度。

[Hello]
[Hello world]

目前

[Hello                   ]
[Hello world             ]

https://jsfiddle.net/v6cgLjbd/8/

<span class='box'>
  <span class='item'>Hello</span>
  <span class='item'>Hello World</span>
  <span class='item'>Hello lOOOOONG text</span>
</span>

.box {
  height: 200px;
  width: auto;
  border: 1px solid red;
  display: flex;
  flex-direction: column;
}

.item {
  background-color: gray;
  flex: 0 0 auto;
  width: auto;
}

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    您需要在 flex-container 上添加 align-items: flex-start。当您在父元素上使用flex-direction: column,在子元素上使用flex 属性时,您控制的是高度而不是宽度。

    .box {
      height: 200px;
      border: 1px solid red;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
    }
    
    .item {
      background-color: gray;
    }
    <span class='box'>
      <span class='item'>Hello</span>
      <span class='item'>Hello World</span>
      <span class='item'>Hello lOOOOONG text</span>
    </span>

    【讨论】:

    • 非常感谢!我不知道 align-items 对宽度有影响。很高兴知道。
    • 不客气。
    猜你喜欢
    • 2017-12-29
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    相关资源
    最近更新 更多