"Create a flexible CSS grid with a dynamically changing number of rows and customizble

I am currently working on a project that involves creating a dynamic grid layout with two resizable columns, namely #red-container and #green-container. The goal is to make each column resizable horizontally while also allowing the main container #container to be resized vertically. When resizing the container, the height of the child elements should adjust accordingly. Both #red-container and #green-container consist of cells that are added dynamically in a row-wise manner using a JavaScript function. Here is the code snippet demonstrating my current implementation:

function addCell(color) {
  let container = document.getElementById(color + "-container");
  
  let cell = document.createElement("div");
  cell.innerText = color;
  container.appendChild(cell).className = "container-item";
}
#container {
  border: 1px solid #ddd;
  display: flex;
  flex-grow: 1;
  flex-direction: row;
  height: 50vh;
  resize: vertical;
  overflow: auto;
}

#red-container,
#green-container {
  flex-grow: 1;
  display: grid;
  grid-auto-flow: row;
  margin: 10px;
  resize: horizontal;
  overflow: auto;
}

#red-container { 
  border: 1px solid red; 
}

#green-container { 
  border: 1px solid green; 
}

.container-item {
  padding: 10px;
  border: 1px solid black;
}
<button onclick="addCell('red')">add red cell</button>
<button onclick="addCell('green')">add green cell</button>

<div id="container">
  <div id="red-container"></div>
  <div id="green-container"></div>
</div>

Despite the current functionality, I have encountered two problems:

  1. Clicking "add red cell" for the first time increases the width of #red-container.
  2. Adjusting the widths of the red and green containers is inconsistent, and I am unable to reduce the width of the red container below 50%.

If you have any solutions to these issues or suggestions for optimizing the CSS code (particularly in eliminating duplicates in #red-container and #green-container), your feedback would be greatly appreciated!

Answer №1

Make the red container resizable with an initial width set to 50% and apply flex-grow:1 to the green container

function createBox(color) {
  let container = document.getElementById(color + "-container");
  
  let box = document.createElement("div");
  box.innerText = color;
  container.appendChild(box).className = "container-item";
}
#container {
  border: 1px solid #ddd;
  display: flex;
  gap: 10px;
  padding: 10px;
  height: 50vh;
  resize: vertical;
  overflow: auto;
}

#green-container,
#red-container {
  display: grid;
  overflow: auto;
}
#red-container {
  border: 1px solid red;
  width: 50%;
  resize: horizontal; 
}
#green-container {
  border: 1px solid green;
  flex-grow: 1;
}


.container-item {
  padding: 10px;
  border: 1px solid black;
}
<button onclick="createBox('red')">add red box</button>
<button onclick="createBox('green')">add green box</button>

<div id="container">
  <div id="red-container"></div>
  <div id="green-container"></div>
</div>

Answer №2

try these steps to resolve the issue:

  1. Set the #container with grid-template-columns: 1fr 1fr; so that the child will always be half-width regardless of other factors.

If you opt for flex, it only expands to 1 but may not always be precisely half, hence grid layout is recommended.

  1. To prevent repetitive code, combine the two selectors into one using a , (comma)
    #red-container, #green-container

additional tips:

  1. Add box-sizing: border-box to avoid issues when adding padding or similar properties.

  2. Avoid specifying grid-auto-flow: row as grid defaults to row anyway.

  3. Utilize gap instead of margin in grid/flex layouts to maintain consistent spacing.
    If using margin, double the specified value will be applied.


here's the corrected code:

function addCell(color) {
  let container = document.getElementById(color + "-container");

  let cell = document.createElement("div");
  cell.innerText = color;
  container.appendChild(cell).className = "container-item";
}
* {
  box-sizing: border-box;
}

#container {
  border: 1px solid #ddd;
  display: grid;
  grid-template-columns: 1fr 1fr;
  height: 50vh;
  resize: vertical;
  overflow: auto;
  gap: 10px;
  /* if you want like before, here in gap: write 20px */
  padding: 10px;
}

#red-container,
#green-container {
  display: grid;
  resize: horizontal;
  overflow: auto;
}

#red-container {
  border: 1px solid red;
}

#green-container {
  border: 1px solid green;
}

.container-item {
  padding: 10px;
  border: 1px solid black;
}
<button onclick="addCell('red')">add red cell</button>
<button onclick="addCell('green')">add green cell</button>

<div id="container">
  <div id="red-container"></div>
  <div id="green-container"></div>
</div>

If any part is unclear, feel free to leave a comment and I'll provide clarification
Here are some helpful resources for reference:

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

What is the method for generating an oval shape with a border-radius in CSS?

Is there a way to create an oval shape instead of a rectangle with rounded edges using CSS? Below is the code snippet I have been working with: div { position: fixed; border-radius: 25px; background: rgba(0,0,0,.5) width: 100px; height: 50px; ...

What is the best way to incorporate a PHP file into an HTML file?

Below is the code snippet from my index.php: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Voting Page</title> <script type="text/javascript" src="js/jquer ...

Multi-object retrieval feature in Material Dialog

I am encountering an issue with Material Dialog when confirming the action to "remove row" in a table. Initially, removing from the dialog works fine and deletes a row. However, after closing the dialog and re-calling it for the second time, the removal ac ...

Menu options submerged beneath the surface of a concealed container with overflow property

Attempting to enhance the ui-grid by adding more options to each row using the "3 dots" approach. However, encountered an issue where the dropdown menu extends beyond the screen due to the use of position: absolute. Unable to switch to position: relative b ...

Vue 3 has a known issue where scoped styles do not get applied correctly within the content of a <slot> element

Utilizing the Oruga and Storybook libraries for creating Vue 3 components. The code in the Vue file looks like this: <template> <o-radio v-bind="$props" v-model="model"> <slot /> </o-radio> </template ...

Try using Bootstrap 4 Carousel columns instead of the traditional carousel-item

Is it possible to use Bootstrap to display grid columns or rows within a Carousel instead of carousel-items? The concept involves having intricate grid column structures that rotate like carousel-items. For instance, if we have the following grid: <div ...

How can you transfer data from a jQuery function to a designated div element?

I'm struggling to transfer data from a function to a specific div, but I can't seem to make it work. I'm in the process of creating a gallery viewer and all I want is to pass the counter variable, which I use to display images, and the total ...

Decoding HTML with PHP

I'm facing an issue with creating a Web page Parser. The structure of the page is as follows: <TABLE WIDTH=80%> <tr><td colspan=7><BR><BR></td></tr> <TR> <Td colspan=7><FONT FACE="arial" align ...

ToggleButton4 Framework is a user-friendly tool for creating interactive

I am currently working with Bootstrap 4 to design a toggle button; however, when I click the button, the checkbox does not update, despite the fact that the active class is being applied. Even when I use $('.btn-group-toggle').button('toggl ...

CSS techniques for arranging images with varying sizes into a tiled layout

I have a collection of images that I want to arrange in a tiled layout, similar to the one shown in this image. These images consist of 3 photos with identical width and height, except for one which is larger and should occupy double the space compared to ...

Get rid of angular comments in an HTML document

Is it feasible to eliminate or deactivate the HTML comments generated by Angular? <ol class="items"> <!-- ngRepeat: item in list | orderBy:'time':true --> </ol> This is disrupting CSS rules that utilize the :empty pseudo c ...

I'm looking for a way to have an element shift in a particular direction only when two keys are pressed simultaneously

Having trouble moving a square diagonally when two keys are pressed simultaneously. Trying to create an if statement that detects both key presses at the same time and triggers the movement. However, all attempts have failed so far, leaving uncertainty abo ...

Eliminate border around image

I've been trying to get rid of the image border using different methods img { border: 0px; } I even attempted to remove it from the browser console with this code border: none !important This is what my html code looks like <div id="startD ...

Guide to sending DevExtreme data grids to ASP.NET MVC controllers

Currently, I am utilizing a datagrid with DevExtreme. I am wondering how I can pass the datagrid to my controller in ASP.NET MVC. In my view, I have attempted the following: @using (Html.BeginForm("action-name", "controller-name", FormMethod.Post)) { ...

if the checkbox is selected, navigate to the displayed section

In my scenario, I have a total of 5 checkboxes and corresponding to each checkbox, there are 5 div elements. The functionality that I need is that when a checkbox is checked, the associated div should be displayed; otherwise, it should be hidden. The check ...

Using Javascript's .replace() method to preserve HTML elements

This is a JavaScript function I wrote function replaceCharacters(text_input){ return text_input .replace(/O/g, 0) .replace(/I/g, 1) .replace(/o/g, 0) .replace(/i/g, 1) .replace(/t/g, 4) .replace(/d/g, 9) ...

Element obscured by dropdown content now clearly visible thanks to dropdown adjustment

Something strange is happening here - the Add question div shouldn't be visible. It's somehow appearing behind the dropdown content. I've attempted to adjust the z-index of the Add Question div, setting it to a lower number than the dropdown ...

Semantic UI dropdown field not displaying selected option text

I've encountered an issue while working with React Semantic UI. I'm trying to render a dropdown and have configured it so that the selected option's text should display in the field. However, when I choose an option from the dropdown, instea ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...

Ensure that the header stays centered on the page as you scroll horizontally

Below is a given code snippet: header { text-align: center; } /* This section is just for simulation purposes */ p.text { width: 20rem; height: 50rem; } <html> <body> <header> <h1>Page Title</h1> <detail ...