parent element has a grid child element that is overflowing due to CSS

Creating a React app has led me to a situation where I need to exhibit a grid to the user. The definition of this grid is extracted from the backend as an object. My objective is for the page to occupy all available space, with a header and footer in place, while the grid should consume the remaining space between them.

In my scenario, the grid must be structured as a 50 columns by 50 rows layout.

To display certain boxes within the grid, the position (x and y) on the grid along with the number of rows and columns each box needs to encompass are defined.

I was able to achieve this successfully, but then I encountered an issue when attempting to insert images inside these boxes. Strangely, as soon as I incorporate images into the boxes, they expand and cause the grid to overflow its parent container. This behavior is undesired; I want the images to fit within the respective box at their original size.

This marks my first time using the CSS property display: grid, making it evident that there might be gaps in my understanding of its functionality.

If anyone can shed light on why this occurs and how I could modify it to align with my intentions, please share your insights.

Here's a basic example illustrating the issue I faced. Simply uncomment the <img/> line below to observe the overflow:

const elements = [{
    x: 36,
    y: 2,
    rows: 7,
    cols: 7,
  },
  {
    x: 43,
    y: 14,
    rows: 7,
    cols: 7,
  },
  {
    x: 36,
    y: 26,
    rows: 7,
    cols: 7,
}];

const App = () => {
  return ( 
    <div className="App">
      <div className="header">
        <h2>Header</h2>
      </div>

      <div className="grid">
        {elements.map((elt) => (
          <div
            className="grid-elt"
            style={{
              gridColumn: `${elt.x} / ${elt.x + elt.cols}`,
              gridRow: `${elt.y} / ${elt.y + elt.rows}`,
            }}
          >
            {/* uncomment the img to see the overflow */}
            {/* <img
              className="img"
              src="https://cdn-icons-png.flaticon.com/512/13371/13371271.png"
            /> */}
          </div>
        ))}
      </div>

      <div className="footer">
        <h3>Footer</h3>
      </div>
    </div>
  );
};


// Render it
ReactDOM.render(
    <App/>,
    document.getElementById("root")
);
html {
  display: flex;
  width: 100%;
  height: 100%;
  flex: 1;
}

body {
  display: flex;
  flex: 1;
  height: 100%;
  margin: 0;
}

#root {
    display: contents;
}

.App {
  font-family: sans-serif;
  text-align: center;
  background-color: cadetblue;
  display: flex;
  flex: 1;
  flex-direction: column;
  width: 100%;
  height: 100%;
  margin: 0;
}
.header {
  height: 100px;
  background-color: bisque;
}

.footer {
  background-color: blueviolet;
  height: 50px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(50, 1fr);
  grid-template-rows: repeat(50, 1fr);
  height: 100%;
  width: 100%;
}

.grid-elt {
  border: 1px solid red;
}

.grid-elt1 {
  grid-com
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Although I delved into the documentation on display: grid, no definitive clarification regarding my predicament seemed apparent. It’s plausible that the issue arises due to defining the grid cells and rows utilizing repeat(50, 1fr), but this remains uncertain.

Answer №1

A technique to maintain the size of containers regardless of their content is by using position: absolute on images so they do not disrupt the document flow.

The main adjustment I made in your code:

.grid-elt {
  border: 1px solid red;  
  position: relative;     
}

.img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

I assumed that container size should take precedence over image size, leading to a common issue of incorrect aspect ratio.

Here is the complete demo with a button in the header to toggle the visibility of the picture and prove that the box sizes remain unaffected:

const elements = [{
    x: 36,
    y: 2,
    rows: 7,
    cols: 7,
  },
  {
    x: 43,
    y: 14,
    rows: 7,
    cols: 7,
  },
  {
    x: 36,
    y: 26,
    rows: 7,
    cols: 7,
  },
];

const App = () => {

  const toggle = () => {
    const images = document.querySelectorAll('.grid-elt img');
    images.forEach(img => {
      img.style.display = img.style.display === 'none' ? 'block' : 'none';
    });
  };

  return ( 
    <div className="App">
      <div className="header">
        <h2>Header</h2>
        <button onClick={toggle}>show/hide pictures</button>
      </div>

      <div className="grid">
        {elements.map((elt) => (
          <div
            className="grid-elt"
            style={{
              gridColumn: `${elt.x} / ${elt.x + elt.cols}`,
              gridRow: `${elt.y} / ${elt.y + elt.rows}`,
            }}
          >            
            { <img
              className="img"
              src="https://cdn-icons-png.flaticon.com/512/13371/13371271.png"
            />}
          </div>
        ))}
      </div>

      <div className="footer">
        <h3>Footer</h3>
      </div>
    </div>
  );
};


// Render it
ReactDOM.render(
    <App/>,
    document.getElementById("root")
);
html {
  display: flex;
  width: 100%;
  height: 100%;
  flex: 1;
}

body {
  display: flex;
  flex: 1;
  height: 100%;
  margin: 0;
}

#root {
    display: contents;
}

.App {
  font-family: sans-serif;
  text-align: center;
  background-color: cadetblue;
  display: flex;
  flex: 1;
  flex-direction: column;
  width: 100%;
  height: 100%;
  margin: 0;
}

.header {
  height: 100px;
  background-color: bisque;
}

.footer {
  background-color: blueviolet;
  height: 50px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(50, 1fr);
  grid-template-rows: repeat(50, 1fr);
  height: 100%;
  width: 100%;
}

.grid-elt {
  border: 1px solid red;  
  position: relative;     
}

.img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

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

ways to change date format in a React.js application using JavaScript

<b>Choose Date and Time</b><br/> <DateTimeField onChange={this.clockevent} format={"x"}/> clockevent=(newDate)=>{ var dateVal ="/Date("+newDate+")/"; var date = new Date(parseFloat(dateVal.substr(6))); console.log( ...

Using maxDate in Material UI DatePicker Component to set a maximum date limit

I'm having a tough time getting the maxDate property to function properly on the Material UI DatePicker component. It should disable dates after the specified maxDate. In my situation, I needed to set the maxDate to +60 days from the current Date(), ...

Insert information into the React object

Can you lend me a hand with something I'm struggling with? The issue is that when I try to add data to an array using a function, it ends up overriding the existing data instead of appending to the array. I can't figure out what's going wron ...

Exploring ways to enhance the appearance of a Sidebar Widget Navigation using JQuery

When creating navigational items with submenus, such as 'Primary Fees', I added an arrow for visual indication. To enhance user experience, I included an animation that rotates the arrow and highlights the Main Menu item in red upon hovering. Thi ...

Make sure the div is always positioned above everything, including any built-in pop-up windows

When working with two forms, one for user input and the other as a pop-up window to display results, users sometimes close the pop-up window prematurely if they think there is a network issue causing a delay in data execution. To prevent this, I am consi ...

What is the best way to change the orientation of a scanner loop animation to

Currently, I have a CSS style featuring an animation that scans across a line in a loop. My goal is to apply this animation to a horizontal line, but I am struggling to figure out how to rotate the scanner for a horizontal loop. Below is my current code. A ...

Is it possible to utilize relative paths with webpack dev server in React JS projects?

While running the development server on localhost:3000 using npm run start, everything functions as expected. I am utilizing react-scripts and have not ejected the react app. Currently, my goal is to configure the dev server behind a reverse proxy so that ...

Most effective method for designing a reusable <table> appearance

For my project, I need to create multiple tables using data from a database on different pages. I want to maintain a consistent styling throughout these tables: The first and last rows should have a bold font with reversed foreground/background colors. Th ...

Hovering in Javascript

Imagine I have the following code snippet: <div class="class1"> ... random content </div> I want to use JavaScript so that when I hover over that div, a CSS attribute is added: background-color:#ffffe0; border:1px solid #bfbfbf; This is a ...

How can you modify the HTML tags before Bootstrap overrides them?

Imagine having a code snippet like this: <style> #container ul li{ font-size:50px;} .myclass1 ul li{ font-size: 20px;} </style> <div id="container"> <ul> <li> <div class="myclass1"> ...

Changing the name of a radio button dynamically using jQuery

Trying to find a solution like the following: $("input:radio:checked").previous("name", "original_name").attr("name","new_name"); I've experimented with a few methods found here, but keep encountering the error: Object Expected Any assistance would ...

Error message: "Window object not defined during NextJS build process."

Why am I encountering a 'window not defined' error? I haven't referenced window or document in my code, and it runs without issues during development but throws an error during the build process. ReferenceError: window is not defined at ...

Is it possible to include spaces in a JavaScript alert message?

Is it possible to add spaces in an alert message? I have been trying to include spaces in my alert messages, but the alerts do not appear when there are spaces. Example where it works: https://jsfiddle.net/yczrhztg/ Example where it doesn't work: ht ...

Tips for looping through a list in React components?

Currently, I have a function that filters specific cities into the "citiesList" array and then attempts to map them into a dropdown component. However, while the filtering part is successfully executed, the mapping part seems to be failing. citySearched ...

Increase performance by minimizing unnecessary component re-renders in Next.js using memoization

I am currently exploring the behavior of React within Next.js. I have an index.js page that displays one component Homecard three times and a button that increments a value. Each time I click on the button, all Homecard components are re-rendered. index. ...

Align three or more Font Awesome icons in a row at the center

When it comes to center aligning an icon, I typically use margin: auto;, text-align: center;, or left: 50%; transform: translateX(-50%);. However, I've run into a hurdle trying to center align three icons together. I thought applying these techniques ...

Display the value of my JavaScript variable within a div element

I am having trouble displaying the JavaScript variable "dayz" in the results div. When I try to use alert(dayz) after the calculation, it works fine, but I need it to output the dayz variable in the HTML. Can anyone help me with this issue? <html> ...

During my attempt to convert my Slice.js file to ts using the redux toolkit, I encountered some Type-errors

After creating a sample Redux toolkit with JavaScript files, I am now attempting to convert them to TypeScript. Some errors have been resolved, but I am facing issues with the following two errors: The error "Property 'name' does not exist on ty ...

Exploring the .map() Method in ReactJS

Would it be feasible to integrate another Postgres database table into the current mapping displayed in this code? It would be ideal if it could be done using some sort of array function. {items.map(item => ( <tr key={item.id}& ...

Incantation within ng-include | src involving a series of characters

Is there a way to create a URL in ng-include|src by combining an expression and a constant string? I've attempted the code below, but it doesn't seem to be working. <aside ng-include src="{{staticPath}} + 'assets/tpl/products-feed-histor ...