【问题标题】:Flex responsive max-width with space-betweenFlex 响应式最大宽度,中间有空格
【发布时间】:2018-10-27 08:01:32
【问题描述】:

我正在添加 3 个最大宽度为 400 像素的列,并使用 space-between 在它们之间添加空间。

.wrap {
  display: flex;
  flex-wrap: wrap;
  align-content: stretch;
  justify-content: space-between;
}

.item {
  width: 100%;
  max-width: 400px;
}

当我缩小屏幕尺寸时,项目没有响应。他们只是在彼此下方坍塌。如果我删除 flex-wrap 我开始每行获得超过 3 列并且它们低于 400 像素。

如何在 flex 中获得 3 个带有空格的响应列?

不能使用宽度百分比,因为项目之间的空间在任何屏幕尺寸下都必须看起来相同。

【问题讨论】:

  • They just collapse below each other. --> 你期待什么?

标签: css flexbox


【解决方案1】:

如果你不希望它们占据父元素的整个宽度,你应该删除width: 100%。并且由于您在父级上使用 flex,您不妨在子级上使用 flex 属性并拥有这些:

.item {
  flex-basis: 33%;   /* <-- Added in lieu of the width */
  max-width: 400px;
  margin: 0px 5px;   /* <-- Added to give left/right margins */
}

如果您的父母中只有这 3 个孩子,那么您也可以这样做:

.item {
  flex-grow: 1;      /* <-- Lets them grow equally */
  flex-shrink: 1;    /* <-- Lets them shrink equally. OPTIONAL as 1 is the default */
  max-width: 400px;  
  margin: 0px 5px;   /* <-- Added to give left/right margins */
}

最后一个的简写是这样的:

.item {
  flex: 1;           /* <-- Lets them grow/shrink equally */
  max-width: 400px;  
  margin: 0px 5px;   /* <-- Added to give left/right margins */
}

另外,如果父元素中只有这 3 个子元素,如果您不希望子元素换行,则可能需要从 .wrapper 中删除 flex-wrap: wrap;。在这种情况下不会发生这种情况,因为孩子的百分比宽度加起来是 100%。但这可能会令人困惑,并且与您的意图相矛盾。

【讨论】:

    【解决方案2】:

    如果您想要三列,请将您的 .item 声明中的宽度属性更改为 33%,而不是 100%

    JSFiddle example

    目前,您所有的“列”都在争取成为 100% 的父节点。这是来自 css-tricks.com 的出色 explanation of using css flex

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2015-06-09
      • 1970-01-01
      相关资源
      最近更新 更多