【问题标题】:FlexItems not taking up entire space with flex wrapFlexItems 不使用 flex wrap 占用整个空间
【发布时间】:2021-07-02 19:01:28
【问题描述】:

在我问这个问题之前是相关代码。

const App: FC = () => {
  const [boardWidth, _setBoardWidth] = useState<number>(1400);
  const [boardHeight, _setBoardHeight] = useState<number>(1000);
  const [cellWidth, _setCellWidth] = useState<number>(50);
  const [cellHeight, _setCellHeight] = useState<number>(50);
  const [gameBoard, setGameBoard] = useState<number[][]>();

  useEffect(() => {
    setGameBoard(generateGameBoard());
  }, [boardWidth, boardHeight]);

  const generateGameBoard = (): number[][] => {
    const numOfRows: number = boardHeight / cellHeight;
    const numOfColumns: number = boardWidth / cellWidth;
    let board: number[][] = [];

    for (let i = 0; i < numOfRows; i++) {
      board.push(new Array(numOfColumns).fill(Cell.DEAD));
    }

    return board;
  };

  return (
    <div>
      <div
        className="gameBoard"
        style={{ width: boardWidth, height: boardHeight }}
      >
        {gameBoard &&
          gameBoard.map((row) =>
            row.map((c, idx) => (
              <div
                key={idx}
                className={`${c === Cell.ALIVE ? "alive" : "dead"} cell`}
                style={{ height: cellHeight, width: cellWidth }}
              />
            ))
          )}
      </div>
    </div>
  );
};

export default App;

然后是css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
}

#root {
  height: 100vh;
}

.gameBoard {
  border: 1px solid #e0e0e0;
  box-shadow: 2px 3px 5px #e0e0e0;
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
}

.cell {
  background: rgba(0, 0, 0, 0.5);
}

在这种情况下,我希望有一个 50x50 的单元格占据 1400 x 1000 的网格,因此 20 行,每行 28 个单元格。我确实获得了正确数量的单元格并使用 devtools 我可以确认所有内容的大小都正确但由于某种原因,这些行将一个单元格包裹得很短,让我附上一张图片给你看(我在图片中突出显示游戏板边框为红色以方便看到)https://gyazo.com/9a6ceb392816539b58c5ec08105bc305

任何帮助将不胜感激,谢谢

【问题讨论】:

    标签: javascript css reactjs typescript flexbox


    【解决方案1】:

    这是因为您已将所有内容的 box-sizing 设置为 border-box -

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    

    所以,你的游戏板是1400px 宽,带有1px 边框,这意味着盒子的空间量是1400 - 2px = 1398px

    有两种方法可以修复它 -

    • 在游戏板的宽度上增加 2px;或
    • 将gamebord的box-sizing设置为content-box

    Here's a StackBlitz 显示修复的第二个版本。

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2023-01-11
      • 2020-11-13
      • 2020-09-21
      • 2016-01-21
      • 2013-09-03
      • 2017-01-27
      • 2020-07-25
      • 1970-01-01
      相关资源
      最近更新 更多