Issues with FlexItems not fully occupying available space when using flex wrap

Before presenting my question, here is the relevant code snippet:

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;

Next, I will include the corresponding CSS styling:

* {
  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);
}

In this scenario, I expected a grid of 50x50 cells to span a 1400 x 1000 area, resulting in 20 rows with 28 cells each row. However, while the cells are correctly sized, there seems to be an issue where the rows are wrapping one cell short. You can view a screenshot highlighting this border discrepancy at https://gyazo.com/9a6ceb392816539b58c5ec08105bc305.

If anyone could provide assistance with resolving this matter, it would be greatly appreciated. Thank you.

Answer №1

The reason for this issue is due to the box-sizing property being set to border-box for all elements -

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

This means that your gameboard has a width of 1400px with a 1px border, resulting in an available space for boxes of 1400 - 2px = 1398px.

To resolve this, you have two options -

  • Increase the width of the gameboard by an additional 2px; or
  • Change the box-sizing property for the gameboard to content-box

Check out this StackBlitz showcasing the implementation of the second fix.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing the appearance of text by applying a background color solely to its length

After conducting thorough research on the issue, I have come across various solutions that could potentially address it. However, despite my best efforts, I am unable to implement these solutions successfully. The problem at hand involves providing a colo ...

Remove all $.ajax requests from content that has been loaded using $.ajax in jQuery

I'm currently working on a page where users can click a link to load content using $.ajax into a designated container div. However, I've encountered an issue with multiple clicks causing an increase in the number of $.ajax requests and resulting ...

Unable to obtain the vertices of the extremities due to the absence of labels on AxisHelper

My goal is to add labels on AxisHelper in Three.js that rotate along with it. I came across a helpful code snippet from this source: // Axes axes2 = new THREE.AxisHelper(70); // Axes labels addLabelAxes(); // Add axes to zoomScene zoomScene.add(axes2); ...

Unique menu design featuring dynamic floating text and creatively asymmetrical sides

I need help creating a customized menu for my website that resembles the design in this image. https://i.sstatic.net/07Ezu.png The menu layout should consist of three main sections as shown by the dotted boxes: a centered logo, a left side with menu items ...

Loading Ajax dropdown with a preselected value in the dropdown menu

There are two pages, each containing a form. Page 1 - Form A) Includes a dropdown menu (with values populated from the database) and a continue button. <select name="form[formA][]" id="dropdown1"> <option value="1">Option 01</opti ...

shadcn: What is the best way to search for apps by name?

I'm currently working on a budget tracker with the ability for users to filter by app name. Below is the code snippet I am using: [ { "status": "on", "id": "NZMwD83Nxg", "name": "GTA_UA_UAC_Android_01_DAU", "dailyBudget": 800, " ...

Using jQuery to transform English into Latin numerals

I am looking to convert all English/Latin numbers in the body to Persian numbers. I have implemented the following code: $(document).ready(function () { persian = { 0: '۰', 1: '۱', 2: '۲', ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

Activate HTML links with a single click by utilizing AJAX calls

I have developed a unique sidebar menu that uses ajax calls to load pages. <div class="sidebar"> <ul> <li><a href='#' onclick="loadProfile()"><i class="icons user-login"></i>Customer Profile</a& ...

Send the style description to the child component

Is there a way to define a style in a parent component and then pass it to a child component? <style> .teststyle { background-color: red; width: 100px; } </style> I initially thought that if I did not use scoped, the .teststyle ...

Learn how to selectively hide the header from the root layout on a single page in Next.js version 14

I am currently working on an app using Next.js 14 and TypeScript. In my root layout, I have added a header and footer. However, on one of the pages I created, I need to hide the header and footer. import type { Metadata } from "next"; import { In ...

What steps should be taken to correct the misalignment of the closing x symbol in the alert box?

After making adjustments to the line height, the closing x mark on the right now aligns closer to the bottom of the alert message box. I am currently utilizing Bootstrap version 5.0.1. Is there a way for me to vertically center the x mark? Thank you. CSS: ...

Combining React with Passport

Greetings! I am currently in the process of developing my application using React and Node (express). I am now focused on establishing authentication with passport. When working with ejs or other template languages, setting it up seemed relatively straight ...

What is the best way to modify the color of the active tab I have chosen?

I've designed a tab menu using Divs and CSS, but I'm facing an issue with changing the color of the selected tab. I tried adjusting the background color of the .tab class, but it seems to only work for part of the tab... You can view the problem ...

Guide on Creating a Popup Window When the User's Cursor Moves Beyond the Webpage Boundary

Imagine you're browsing a webpage and as you move your mouse towards the "back" button, a window pops up within the webpage area, displaying important information. This is a clever way to grab the user's attention before they leave the website. B ...

Versatile Function for Handling Dropdown Changes

I am faced with the challenge of executing a javascript function when multiple select elements are changed. I want to create a versatile function that can be set as the onchange method for various select elements. The following code accomplishes this task ...

Using the click function in React to narrow down the component map

Currently, I'm working on an exciting project and I've encountered a bit of a challenge that has me stumped. I'm using Axios to fetch data, then rendering it with a .map function. After that, I have a click function that should display only ...

Returning to the initial state after clicking on an element within a repeated set in AngularJS?

I'm currently facing a challenge, mainly due to my lack of understanding in basic AngularJs concepts. The issue arises when I interact with a list of clickable words. When I click on any of these words, their color changes individually thanks to the i ...

Is react-particles-js still compatible for me to integrate?

I recently discovered that the package found here: https://www.npmjs.com/package/react-particles-js has been deprecated. Can I still utilize this package? The codes in question can be viewed at: https://codesandbox.io/s/particle-js-background-forked-woypk ...

insert data into modal's interface

I'm encountering an issue with my code, where the modal is not displaying the values inside the brackets as if they were not bound correctly. Everything else in the ng-repeat seems to be working fine, but for some reason the values are not being displ ...