CSS flex,如何在第一行显示一个项目,在下一行显示两个项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26086515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:37:23  来源:igfitidea点击:

CSS flex, how to display one item on first line and two on the next line

cssflexbox

提问by RoyS

This is a pretty simple question, I guess, but I can't get 3 items in the flex container to display in 2 rows, one in the first row and the other 2 in the second row. This is the CSS for the flex container. It displays the 3 items on a single line, obviously :)

这是一个非常简单的问题,我猜,但我不能让 flex 容器中的 3 个项目显示在 2 行中,一个在第一行,另一个在第二行。这是 flex 容器的 CSS。显然,它在一行上显示了 3 个项目:)

div.intro_container {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}

If flex-wrapis set to wrap, then the 3 items are displayed in a column. I thought the wrap setting was needed to display container items on several lines. I've tried this CSS for the first container item, intending to have it occupy the whole of the first row, but it didn't work

如果flex-wrap设置为wrap,则在列中显示 3 个项目。我认为需要 wrap 设置来在几行上显示容器项目。我已经为第一个容器项尝试了这个 CSS,打算让它占据整个第一行,但它没有用

div.intro_item_1 {
  flex-grow: 3;
}

I've followed the instructions in "CSS-Tricks"but I'm really not sure which combination of commands to use. Any help would be very welcome as I'm puzzled by this.

我已经按照“CSS-Tricks”中的说明进行操作,但我真的不确定要使用哪种命令组合。任何帮助都会非常受欢迎,因为我对此感到困惑。

回答by Nico O

You can do something like this:

你可以这样做:

.flex {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.flex>div {
  flex: 1 0 50%;
}

.flex>div:first-child {
  flex: 0 1 100%;
}
<div class="flex">
  <div>Hi</div>
  <div>Hello</div>
  <div>Hello 2</div>
</div>

Here is a demo: http://jsfiddle.net/73574emn/1/

这是一个演示:http: //jsfiddle.net/73574emn/1/

This model relies on the line-wrap after one "row" is full. Since we set the first item's flex-basisto be 100% it fills the first row completely. Special attention on the flex-wrap: wrap;

此模型依赖于在一个“行”已满后换行。由于我们将第一项设置flex-basis为 100%,因此它完全填充了第一行。特别关注flex-wrap: wrap;

回答by Peter Waegemans

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

Nico O给出的答案是正确的。但是,这不会在 Internet Explorer 10 到 11 和 Firefox 上获得预期的结果。

For IE, I found that changing

对于 IE,我发现改变

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

似乎可以解决问题。不要问我为什么,我还没有深入探讨这个问题,但这可能与 IE 渲染边框或其他东西的方式有关。

In the case of Firefox I solved it by adding

在 Firefox 的情况下,我通过添加解决了它

display: inline-block;

to the items.

到项目。