Is it possible to have the cells in a grid adjust and fill the available space when the size of the grid changes?

Hey there! I'm currently working on creating a dynamic grid but I'm facing an issue with making the cells fill the space between them when the size of the grid changes.

Within my function that generates the grid, I take in the size as a parameter. However, I'm struggling to figure out what needs to be added to the grid-square class in order to achieve the desired effect of filling the entire space.

//get the grid div
const container = document.querySelector("#container");

function changeColor(e) {
  const hoverColor = Math.floor(Math.random() * 16777215).toString(16);
  e.target.style.backgroundColor = "#" + hoverColor;
}

function createDivs(size) {
  //generate grid elements
  for (let i = 0; i < size * size; i++) {
    const newDiv = document.createElement("div");
    newDiv.classList.add("grid-square");
    newDiv.addEventListener("mouseover", changeColor);
    container.appendChild(newDiv);
  }
}

createDivs(2);
* {
  box-sizing: border-box;
}
#container {
  display: flex;
  background-color: rgba(49, 49, 49, 0.281);
  width: 50vw;
  height: 50vh;
  flex-wrap: wrap;
}

.grid-square {
  background-color: white;

  width: 50%;
  aspect-ratio: 1/1;
}

.grid-square:hover {
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Etch a Sketck</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

Answer №1

Here is how I approached it: Instead of using flex box, I switched to grid. Grid includes a property known as grid-template-columns, which allows you to specify the number of columns and their widths. The syntax for this property is

grid-template-columns: repeat(n, 1fr)
, where n represents the desired number of columns.

To dynamically set the column numbers in JavaScript, I utilized a CSS custom property (or a CSS variable) to define the column numbers. To assign values to the custom property, I used the element's style attribute to define it upon loading.

Take a look at the code snippet below:

// Retrieving the grid div
const container = document.querySelector("#container");

function changeColor(e) {
  const hoverColor = Math.floor(Math.random() * 16777215).toString(16);
  e.target.style.backgroundColor = "#" + hoverColor;
}

function createDivs(size) {
  // Creating grid elements
  for (let i = 0; i < size * size; i++) {
    const newDiv = document.createElement("div");
    newDiv.classList.add("grid-square");
    newDiv.addEventListener("mouseover", changeColor);
    container.appendChild(newDiv);
  }
  // Addition made here
  container.style.cssText="--cols: "+size; 
}

createDivs(5);
* {
  box-sizing: border-box;
}
#container {
  /* Addition made here */
  display: grid;
  grid-template-columns: repeat(var(--cols), 1fr);
  /* End of addition */
  background-color: rgba(49, 49, 49, 0.281);
  width: 50vw;
  height: 50vh;
  flex-wrap: wrap;
}

.grid-square {
  background-color: white;
  aspect-ratio: 1/1;
}

.grid-square:hover {
  cursor: pointer;
}
<div id="container"></div>

Answer №2

To solve the issue, the width was specified during the creation of the cells.

//locating the grid container
const container = document.querySelector("#container");

function colorChange(e) {
  const hoverColor = Math.floor(Math.random() * 16777215).toString(16);
  e.target.style.backgroundColor = "#" + hoverColor;
}

function generateDivs(size) {
  //creating grid elements
  for (let i = 0; i < size * size; i++) {
    const newDiv = document.createElement("div");
    newDiv.classList.add("grid-square");
    newDiv.addEventListener("mouseover", colorChange);
    //Specifying the width
    newDiv.style.width = 100 / size + "%";
    container.appendChild(newDiv);
  }
}

generateDivs(6);
* {
  box-sizing: border-box;
}
#container {
  display: flex;
  background-color: rgba(49, 49, 49, 0.281);
  width: 50vw;
  height: 50vh;
  flex-wrap: wrap;
}

.grid-square {
  background-color: white;
  width: 50%;
  aspect-ratio: 1/1;
}

.grid-square:hover {
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Etch a Sketck</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

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

While utilizing Ajax with Spring, it is possible to send a JavaScript object and receive it as a custom object. However, there was an issue with

One of my challenges in Java is working with a custom class that looks like this: public class AddressesVO { private Long addressId; private String address; public Long getAddressId() { return addressId; } public void setAddressId(Long addressId ...

How should a successful post request be properly redirected in React?

I am in the process of learning React and currently working on a small project. I have set up a NodeJS server to handle my requests, and now I am facing an issue with redirecting the user after a successful login. I successfully dispatch an action and upda ...

Extract each line of text from the ul li tags at every level of the hierarchy with the help of

I am looking to extract a list of strings from the ul and li elements with slash (/) separating each level up to the nth level using JavaScript. I attempted to use both the Jquery.map and each functions, but unfortunately, I was unsuccessful. ...

Tips for aligning two separate texts depending on if they appear on the same line or not

Looking to align text B to the right when text A and B are on the same line, but automatically aligning text B to the left if it wraps to the next line due to space constraints. .text-left { float: left; /* Float to the left */ } .text-right { fl ...

Arrange data into columns on a website

In my project, I'm exploring the challenge of creating a square 2 x 2 grid alongside a rectangular column on the right-hand side. While attempting to implement a grid system for the 2 x 2 layout, I encountered issues with the alignment of the rectang ...

Is there a way to remove information with react and axios?

While working on a project, I encountered an issue with using .map() to create a list. When I console log the user._id on my backend, it displays all the ids instead of just the one I want to use for deleting individual posts by clicking a button. Each pos ...

Evolutionary JavaScript Adaptations

I am currently working on an HTML project that involves the use of JavaScript with JQuery. In my project, I will be including a map showcasing different images such as 'Abstract', 'Animals', 'Beach' and more. var images = { & ...

Integrating md-chips md-separator-keys with md-autocomplete: A step-by-step guide

My experience with using md-chips and md-autocomplete reveals an issue: when I incorporate md-separator-keys, it functions as expected. However, upon adding md-autocomplete, the md-separator-keys functionality ceases to work. This is how my code is struct ...

Utilizing Semantic HTML to Showcase a Product Comparison

As I prepare to showcase various products on a website for customers to choose from, each with its own name, description, and list of pros and cons compared to other products, I find myself unsure about the best way to structure the HTML. While headings a ...

Deciphering the Components of Web Applications: Express.js, Angular.js, and the MVC Puzzle

After exploring numerous discussions on Stack Overflow regarding the integration of Express.js with Angular.js and the presence of dual MVC components in both the client and server sides of web applications, I have found myself feeling somewhat perplexed. ...

Implementing the row delete function in MUI DataGrid using JavaScript

My grid has a delete icon button in each row, but it's not deleting the row. Can someone please help me with this issue? I'm working on a todo app where each row should have its own delete button. I'm struggling to connect the deleteTodo co ...

Is there a way to swap out multiple characters within a string when using ng-repeat in AngularJS?

How can I replace multiple characters in a string using ng-repeat in AngularJS? I've tried the following code, but it's not working. I need to remove #, _, and . from the strings in my list. How can I achieve this in AngularJS? <body> &l ...

Do the "Save to Drive" buttons require manual cleaning?

Utilizing the Google Drive API for JavaScript within a VueJS application can be done as follows: In your index.html <script type="text/javascript"> window.___gcfg = { parsetags: 'explicit', lang: 'en-US' }; </scri ...

Sending an array of properties to a child component

I am attempting to pass an array of objects from a parent component to a child component as a prop, then iterate over it using map and display the items in the child component. However, when I try to use map on the array nothing is happening, even though ...

Mongoose Alert Utility Directive

const mongoose = require('mongoose'); module.exports = { init: () => { const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false, reconnectTries: Number.MA ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

Combine multiple arrays in JavaScript into a single array

Here is the array I am working with: array = ['bla', ['ble', 'bli'], 'blo', ['blu']] I need to transform it into this format: array = ['bla', 'ble', 'bli', 'blo', &a ...

What is the method for developing a Typescript-connected High-Order React Component with Redux?

I am looking to develop a React Higher-Order Component that can safeguard routes within my application from unauthorized users without an access token. I aim to use this HOC to wrap a Component like so in the parent component: <Route exact path ...

Step by step guide on integrating current locations in Leaflet OpenStreetMap within an Angular application

I am currently working on an Angular application that incorporates a map using Leaflet OpenStreetMap. I want to display the real-time latitude and longitude for the map, which should update based on the location. Can someone advise me on how to add the cur ...

Implementing Browser Back or Back button in AngularJS

Currently, I am developing an application that utilizes route methods to navigate between webpages for different modules. Essentially, it is a single page application with route methods responsible for loading the HTML content in the body section. The iss ...