如何制作不同大小的弹性项目以在包裹时填充父级

问题描述 投票:2回答:2

我有以下模板:

<div id="row">
  <div id="longer"></div>
  <div id="shorter"></div>
</div>

当它们在同一行时,我希望longer的宽度是shorter的两倍,所以我应用了以下CSS:

#row {
  display: flex;
  flex-wrap: wrap;
}

#longer {
  flex: 1 0;
}

#shorter {
  flex: 0.5 0;
}

这似乎工作得很好,但是当shorter被包裹时,它只占新行的50%,即使它是该行中唯一的项目。

我想shorter填满整行,如果它是该行中唯一的项目。

没有媒体查询可以实现这一点吗?

Plunker link

html css html5 css3 flexbox
2个回答
3
投票

如果孩子的flex-grow值之和小于1,则它们不会填充整个父级的宽度,而只会填充相应的分数。

您可以将它们乘以相同的比例,使它们至少为1:

#row {
  display: flex;
  flex-wrap: wrap;
}

#longer {
  flex: 2 0;
}

#shorter {
  flex: 1 0;
}


/* Just for demo */

#row div {
  white-space: nowrap;
}

#row div:nth-child(1) {
  background: green;
}

#row div:nth-child(2) {
  background: red;
}
<div id="row">
  <div id="longer">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
  <div id="shorter">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
</div>

2
投票

使它flex: 2 0flex: 1 0 - 分数flex-growflex-shrink只会弯曲flex轴的可用空间的一小部分。见下面的演示:

body {
  display: flex;
}

#row {
  flex: 1 0;
  display: flex;
  flex-wrap: wrap;
}

#longer {
  flex: 2 0;
  background-color: lightgreen;
}

#shorter {
  flex: 1 0;
  background-color: lightblue;
}
<div id="row">
  <div id="longer">
    this_is_the_longer_div_asdasdasdasdasdasdasdasdasdasdasdasdasdasdasd
  </div>
  <div id="shorter">
    this_should_fill_parent_width_when_wrapped
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.