I have a very simple web page:
<body>
<h1> Welcome to storyblocks alpha</h1>
<div id="blockport"></div>
</body>
I have some javascript which adds a child DIV and a few child elements:
function testDisplay() {
alert("This script will run.");
let box = document.getElementById("blockport")
console.log(box);
let node=document.createElement("div");
node.style.backgroundColor="red";
box.prepend(node);
node.className="primitive";
let header = document.createElement("h")
header.innerHTML = "This is a header!"
header.style.position="relative";
header.style.top="100px";
node.prepend(header);
let header2 = document.createElement("h")
header2.style.position="relative";
header2.style.top="100px";
header2.innerHTML = "Testing 1 2 3 ";
node.append(document.createElement("br"));
node.appendChild(header2);
And the CSS class referred to is:
.primitive {
background-color: blue;
border-style: inset;
position: absolute;
cursor: grab;
width: fit-content;
height: fit-content;
}
The problem I have comes from these two lines of code:
header.style.top="100px";
...
header2.style.top="100px";
Without them the display looks like this:

However, when the those lines are included, it looks like this:
This problem persists through various changes, such as position: relative in `.primitive’, among others.
How can I make the node element with the red background expand to cover changes to "top" of it’s children? If I try the .marginTop or .paddingTop property, it seems to have no effect on the final display (although .margin will make the div wider.)
I can actually write some javascript that chooses the size of the let node = ... element, but this is complicated and seems to violate the KISS (keep it simple, stupid) principle if the browsers will do this for me.
How can I make the div expand downwards automatically? Or do I simply need to compute the height of the node element in javascript?
>Solution :
I have added style.display = "block" and removed style.position and used marginTop instead of top.
Try this:
function testDisplay() {
alert("This script will run.");
let box = document.getElementById("blockport")
console.log(box);
let node = document.createElement("div");
node.style.backgroundColor = "red";
box.prepend(node);
node.className = "primitive";
let header = document.createElement("h")
header.innerHTML = "This is a header!"
header.style.display = "block";
header.style.marginTop = "100px";
node.prepend(header);
let header2 = document.createElement("h")
header2.style.display = "block";
header2.style.marginTop = "100px";
header2.innerHTML = "Testing 1 2 3 ";
node.append(document.createElement("br"));
node.appendChild(header2);
}
testDisplay()
.primitive {
background-color: blue;
border-style: inset;
position: absolute;
cursor: grab;
width: fit-content;
height: fit-content;
}
<body>
<h1> Welcome to storyblocks alpha</h1>
<div id="blockport"></div>
</body>
