I would like to set up an HTML page programmatically using JavaScript but I am running into a styling issue with margins. Here's a minimal example:
window.onload = function() {
var div0 = document.getElementById('box2');
div0.style.border = '1px solid black';
var div1 = document.createElement('div');
div0.appendChild(div1);
div1.innerHTML = "This is programmatic";
div1.style.width = '300px';
div1.style.height = '200px';
div1.style.background = 'pink';
div2.style.marginTop = '20px';
div2.style.marginLeft = '20px';
};
<div id="box1" style="border:1px solid black">
<div style="width:300px;height:200px;background:lightgreen;margin-left:20px;margin-top:20px">
This is regular styled HTML</div>
</div>
<div id="box2"></div>
This displays as follows:
The programmatic version (pink) appears to be ignoring the margins. Is there something different about an element that's created programmatically? I can see no differences in the styles reported for the 2 divs.