【问题标题】:Set the maximum amount of children in a flexbox设置 flexbox 中子元素的最大数量
【发布时间】:2021-09-16 12:32:49
【问题描述】:
.Cards {
    justify-content: center;
    display: flex;
    align-items: center;
    text-align: center;
    align-items: center;
    flex-direction: row;
    flex-wrap: wrap;
    .Card {
        text-align: center;
        padding: 20px;
        flex: 1 0 50%; // !
    }
}

我试图让这个 flexbox 设置每行最多 2 个孩子。即使使用flex: 1 0 50%,我也得到了这个:

为什么会这样?即使添加width: 50px 也不起作用。

【问题讨论】:

  • 你希望我们猜到你在 html 中写了什么?请提供一个最少的可重复示例或至少显示您的代码。

标签: css reactjs sass flexbox


【解决方案1】:

css 中的一个技巧:

width: calc(100%/2);

把这个放入卡片

.Cards{
  ...
  .Card{
    width: calc(100%/2);
    ...
  }
}

更多关于计算:https://developer.mozilla.org/en-US/docs/Web/CSS/calc()

新方法,也很容易阅读。

【讨论】:

  • 这不就是width: 50%的意思吗?
  • 如果他要求(他没有)7 件或 3 件?然后?我认为这更具可读性。这就是为什么? @AreebKhan
  • @MaifeeUlAsad 项目的数量在这里没有任何改变。 @areebKhan 是的,这里的意思是50%,但知道它仍然是一件好事^^
  • @QuentinGrisel ,让我们说 7、100/7=14.2814.28*7=99.960.04 不是一个重要的值,仍然缺少一些东西,这就是我的全部想说..
【解决方案2】:

您没有为您提供 html 代码,所以我认为没问题。现在看到你写的东西,你需要包装你的物品(你做到了),但还需要给你的物品一个尺寸。您写的大小以像素为单位,不代表屏幕的一半,您可能打错了。这是您所需的最低 css:

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

.container > * {
  width: 50%;
} 

这里有一个组件来说明:

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

const App = () => {
  return (
    <div className="container">
      <div>Hello</div>
      <div>world</div>
      <div>Here</div>
      <div>I</div>
      <div>Am</div>
    </div>
  );
};

render(<App />, document.getElementById('root'));

这里是the repro on Stackblitz

【讨论】:

    猜你喜欢
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多