Utilizing JavaScript and Flexbox to generate a 16x16 grid within a div element

I am facing an issue with stretching my grids horizontally in order to fit perfectly within my container. The objective is to create a 16/16 grid using flexbox and dynamically generate divs in JavaScript, which will then be placed into a container (sketch-screen) in HTML. However, I am encountering difficulty in achieving the desired stretch. I attempted to use 'flex:1' and '1 1 auto' on the divs within the container, but it did not yield the expected results. My goal is to have the grids fill all available space within the container so they appear as squares rather than rectangles. Additionally, I would like to have the flexibility to adjust the size of the grid.

function makeGrids(size) {
  let screen = document.querySelector(".sketch-screen");
  for (let i = 0; i < size; i++) {
    let column = document.createElement("div");
    column.classList.add("column");
    for (let j = 1; j <= size; j++) {
      let row = document.createElement("div");
      row.classList.add("row");
      row.style.border = "2px solid black";
      row.innerText = (i * size) + j;
      column.appendChild(row);
    }
    screen.appendChild(column);
  }
}

makeGrids(16);
* {
  margin: 0;
  padding: 0;
}

body {
  background-color: #7d7d7d;
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
}

footer {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: auto;
  background-color: #555454;
  padding: 12px;
  margin-top: 16px;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 16px;
}

.sketch-container {
  display: flex;
  justify-content: center;
  width: 800px;
  height: 800px;
  background-color: #991101;
  padding-top: 50px;
}

.sketch-screen {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width: 600px;
  height: 600px;
  background-color: #bfbfbf;
}

.sketch-screen>div {
  height: auto;
  flex: 1 0 auto;
}
<div class="container">
  <div class="sketch-container">
    <div class="sketch-screen">

    </div>
  </div>
</div>
<footer>
  <p>Design by 2023</p>
</footer>

Answer №1

To ensure proper layout, it is essential to also set your .column elements as vertical flexboxes:

.sketch-screen>div {
  height: auto;
  flex: 1 0 auto;

  /* specify columns as vertical flexboxes */
  display: flex;
  flex-direction: column;
}

.sketch-screen>div>* {
  /* evenly distribute rows */
  flex: 1;
}

function createGrids(size) {
  let screen = document.querySelector(".sketch-screen");
  for (let i = 0; i < size; i++) {
    let column = document.createElement("div");
    column.classList.add("column");
    for (let j = 1; j <= size; j++) {
      let row = document.createElement("div");
      row.classList.add("row");
      row.style.border = "2px solid black";
      row.innerText = (i * size) + j;
      column.appendChild(row);
    }
    screen.appendChild(column);
  }
}

createGrids(16);
* {
  margin: 0;
  padding: 0;
}

body {
  background-color: #7d7d7d;
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
}

footer {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: auto;
  background-color: #555454;
  padding: 12px;
  margin-top: 16px;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 16px;
}

.sketch-container {
  display: flex;
  justify-content: center;
  width: 800px;
  height: 800px;
  background-color: #991101;
  padding-top: 50px;
}

.sketch-screen {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width: 600px;
  height: 600px;
  background-color: #bfbfbf;
}

.sketch-screen>div {
  height: auto;
  flex: 1 0 auto;

  /* specify columns as vertical flexboxes */
  display: flex;
  flex-direction: column;
}

.sketch-screen>div>* {
  /* evenly distribute rows */
  flex: 1;
}
<div class="container">
  <div class="sketch-container">
    <div class="sketch-screen">

    </div>
  </div>
</div>
<footer>
  <p>Design by 2023</p>
</footer>

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

When a function is triggered automatically, it sends back an HTML response by default, whereas executing it manually will yield

My current setup involves an action named fetchUserPermissions that retrieves a permission set from an api endpoint using axios. This action is triggered by another action called init, which is automatically executed through the utility dispatchActionForAl ...

Tips for keeping the footer anchored to the bottom of the page, even when the window size is minimized

I'm facing a bit of a challenge with this HTML issue. Currently, I have a webpage and I want the footer to always remain at the bottom with a certain distance from the elements above it, specifically the Twitter and G+ divs. Please refer to the CSS ...

What specific occurrences or processes initiate an HTTP POST request?

When considering the code snippet from an express app: var express = require('express'); var router = express.Router(); var standupCtrl = require('../controllers/standup.server.controller'); /* GET home page. */ router.get('/&a ...

Display chart labels are constantly visible in Vue Chart JS

In my Vue.js JavaScript application, I am working on setting up a chart where I want the labels and chart information to be visible at all times without requiring mouse hover. Check out this image of the chart. This is the code snippet for my chart: < ...

Can you explain the distinction between align-content and align-items?

Can you explain the distinction between align-items and align-content? ...

Achieving a layered effect with elements overlapping onto another div

Looking for a way to create a design where the text in id="text-field" overlaps with id="image-field". Need some guidance on how to achieve this effect. Any help is appreciated. <!DOCTYPE html> <html> <body> <div class=" ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

I can't seem to get my code to work more than once

My code seems to be working only once. This is the HTML code snippet I am using: <span id="0" class="add-title">add title</span> And here is my JavaScript code: jQuery(document).ready(function($) { var iTitlesArray = []; $(document ...

Ways to make <li> elements display inline with React Bootstrap Rows and Columns

I have some content that I need to format and display in a horizontal list. When I only use HTML elements in the list, it appears horizontally as expected. However, when I incorporate React Bootstrap grid layout components like Row and Column, the list dis ...

Encountering the 404 Not Found error when trying to fetch the Next.js API Route from the app

Currently facing difficulties with the routing in Next.js 13's app. Every time I attempt to access it, for instance via Postman, I keep getting a 404 Not Found error. This is my file structure: https://i.stack.imgur.com/ZWrlb.png An example of one ...

What is the method for incorporating PHP's header() function within PayPal JavaScript code?

I'm currently working on integrating Paypal with my website and I've run into some issues handling the various messages sent by Paypal, such as success, failed, and cancelled transactions. Below is a snippet of the Paypal JS code where it manage ...

Enhancing Nested Objects using Mongoose

When attempting to update nested objects using Mongoose, the request I receive appears like this: { 'example[apple]': 'false', 'example[pear]': 'false', 'example[banana]': 'false', 'example[ ...

Combine multiple .less files into a single .less file without the need for recompilation

I currently have 3 different .less files (1file.less, 2file.less, 3file.less) that I want to combine into a single file called base.less. To import these files into base.less, I am using the @import "1file.less" method. However, upon inspecting the pa ...

An error has occurred in Angular5 and Three.js: 'Scene1' property is undefined

Running into an issue with my angular5 website integrated with Three.js. I keep getting an error message that says: Cannot read property 'Scene1' of undefined when trying to add an object to the Scene. Any suggestions on how to properly define th ...

Create a "load additional data" button

I'm working on building my blog and I've run into a roadblock while trying to implement a load more button. Here's what I currently have: actions: { LOAD_ARTICLE_LIST: function ({ commit }) { axios.get('someurl/articles') ...

Leveraging JavaScript along with the jQuery library and API to showcase information related to

Hey there! I have been working on this API that shows upcoming concerts, but I'm struggling to display the images associated with each concert. I've tried using for loops to iterate through the objects, and it seems like every sixth element has ...

How can one utilize Codemirror code folding while avoiding the use of "[ ]"?

I am looking forward to implementing Codemirror codefolding for folding only braces { and }, as well as comments. However, I am facing an issue where it also folds square brackets [ and ]. Since square brackets are usually part of one-line statements, I do ...

Utilizing AngularJS: Binding stateParams value to custom data within state objects

Following the guidelines here, I am setting a page title in my state object. $stateProvider .state('project', { url: '/projects/:origin/:owner/:name', template: '<project></project>', data : { pageTi ...

Assign the input value to the success callback for the ajax request

I am facing an issue with setting the data returned from a success callback in an AJAX request as an input value. It seems like this problem is arising because I am using the AJAX request within an event function (.on). For updating the specific input, I b ...

Clear the cache of a query in React Query without having to fetch it again

Within my React app, I have implemented React Query in the following manner: const { data, status } = useQuery(key, queryFunc, { staleTime: 1 * 60 * 1000 }); In order to invalidate a specific key in the cache based on the value of the data, specifical ...