【问题标题】:Is it possible to have a single flexbox item be multiline?是否可以将单个 flexbox 项设置为多行?
【发布时间】:2017-12-14 07:36:23
【问题描述】:

我想使用 CSS flexbox 实现这个精确的 UI:

我的 DOM 看起来像这样:

<container>
  <item>The</item>
  <item>Quick</item>
  <item>brown fox jumps over the lazy</item>
  <item>dog</item>
</container>

请注意,有些项目足够长,可以多行,而其他项目足够短,应该在同一行。

据我所知,实现此 UI 的方法只有一种,那就是删除项目之间的空格:

<container>
  <item>The</item><item>Quick</item><item>brown fox jumps over the lazy</item><item>dog</item>
</container>

<style>
container {
  max-width: 150px;
  display: block;
}

item {
  color: white;
  padding: 7px;
  line-height: 2.0;
  display: inline;
}

item:nth-child(1) {
  background: red;
}

item:nth-child(2) {
  background: green;
}

item:nth-child(3) {
  background: orange;
}

item:nth-child(4) {
  background: blue;
}
</style>

这在两个帐户上留下了一些不足之处:

  1. 将所有项目强制放在一行中会使 DOM 难以阅读,尤其是在更复杂的场景中。
  2. 它需要修改 line-height 以达到所需的高度。

我很想使用 CSS Flexbox 来实现这个精确的 UI,但我找不到让 Flexbox 像这样在多行上换行的方法。可能吗?

【问题讨论】:

  • 不,单独使用 Flexbox 是不可能的,但是如果你添加一个脚本,你可以做到这一点,脚本可以包装每个单词。

标签: html css flexbox


【解决方案1】:

使用 flexbox 完成您所要求的任务并保持相同的 html 结构将是一种复杂的方法,这根本不可能。你can't just break a flex-item to wrap 在不同的行。如果你想让他们换行,他们首先需要be a seperate item

我已经修改了 html 以展示它仍然可以用来实现这一点。

container {
  display: flex;
  flex-wrap: wrap;
}

break {
  flex-basis: 100%;
  width: 0px;
  height: 0px;
  overflow: hidden;
  display: inline-block;
}

item:nth-child(n+1) {
  background: red;
}

item:nth-child(n+2) {
  background: green;
}

item:nth-child(n+3){
  background: yellow;
}
item:nth-child(n+8){
  background: blue;
}
<container>
  <item>The</item>
  <item>Quick</item>
  <item>brown</item>
  <break></break>
  <item>fox jumps over the </item>
  <break></break>
  <item>lazy</item>
  <item>dog</item>
</container>

【讨论】:

  • 我担心这个解决方案并不令人满意,因为“棕色”和“懒惰”这两个词需要成为“狐狸跳过”的同一元素的一部分。在现实生活中,内容来自数据库。
  • @MartynChamberlin 就像我说的,你不能只使用 flexbox 来破坏项目。它不是那样工作的,但我展示了如何在需要时解决它,并且 flexbox 不是在这种情况下使用的理想选择。
  • 有道理。感谢您的参与!
猜你喜欢
  • 2015-05-03
  • 2012-06-21
  • 2011-02-22
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多