A follow-up post from CSS grid with dynamic number of rows and adjustable width. I am trying to add some content to each container-item dynamically by calling populateCell
which is fired when the user either clicks on the populate red cell
or populate green cell
button. The implementation I have for this is the following:
function addCell(color) {
let container = document.getElementById(color + "-container");
let cell = document.createElement("div");
cell.innerText = color;
container.appendChild(cell).className = "container-item";
}
function populateCell(color) {
let container = document.getElementById(color + "-container");
let children = container.children;
let n = Math.floor(Math.random() * children.length); // random child
children.item(n).innerHTML = `
<div class="confined-div" style="height: 100%; width: 100%">
<fieldset>
<div style="overflow:auto;">
placeholder
</div>
</fieldset>
<input style="margin: 2px;">
<button>Button</button>
</div>
`;
}
#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;
}
.confined-div {
display: flex;
flex-direction: column;
min-width: 0;
}
<button onclick="addCell('red')">add red cell</button>
<button onclick="addCell('green')">add green cell</button>
<button onclick="populateCell('red')">populate random red cell</button>
<button onclick="populateCell('green')">populate random green cell</button>
<div id="container">
<div id="red-container"></div>
<div id="green-container"></div>
</div>
The problem I have is that the content I am adding, i.e., confined-div
, does not respect the width and height of the cells which causes the cells to expand and the content inside confined-div
does not shrink to fit. Ideally, I would want the layout to stay the same after populating the cells.
I am looking for a generic solution that works for any type of content, for instance a canvas
element:
function populateCell(color) {
let container = document.getElementById(color + "-container");
let children = container.children;
let n = Math.floor(Math.random() * children.length); // random child
children.item(n).innerHTML = `
<div class="confined-div">
<canvas></canvas>
</div>
`;
}
Is it possible to specify these kind of constraints? Any suggestions are welcome.
EDIT
Changed style of .confined-div
as suggested by Temani.