INuke
INuke

Reputation: 303

FlexItems not taking up entire space with flex wrap

Before I ask the question here is relevant code.

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;

and then the 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);
}

What I would expect is to have a gird of 50x50 cells taking up in this case a 1400 x 1000 grid, so 20 rows with 28 cells in each row. I do get the right amount of cells and using devtools I can confirm everything is the right size BUT for some reason the rows are wrapping one cell short let me attach a picture to show you (im highlighting the gameboard border red in the picture for ease of seeing) https://gyazo.com/9a6ceb392816539b58c5ec08105bc305

any help would be appreciated, thanks

Upvotes: 0

Views: 29

Answers (1)

gerrod
gerrod

Reputation: 6627

It's because you've set the box-sizing of everything to be border-box -

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

So, your gameboard is 1400px wide with a 1px border, which means the amount of space for boxes is 1400 - 2px = 1398px.

There are two options to fix it -

  • Add an extra 2px to the width of the gameboard; or
  • Set the box-sizing for the gamebord to content-box

Here's a StackBlitz showing the second version of the fix in action.

Upvotes: 1

Related Questions