I have multiple identical div
elements with their display
property set to inline-block
. I am aware that by default, inline-block
elements come with some margin around them, so I expect to see some empty space surrounding these elements (I am not looking to remove this space).
If I manually include them in the html file, they behave as anticipated.
* {
margin: 0;
padding: 0;
}
div.box {
width: 100px;
height: 40px;
background: red;
display: inline-block;
}
<div tabindex="1" class='box'></div>
<div class='box'></div>
<div class='box'></div>
However, when I begin adding them via JavaScript, the top and bottom margins remain unchanged, but the left and right margins seem to disappear.
In the provided code snippet, after tabbing into the first element and pressing enter, a new div
is created and added to the DOM
, but subsequent additions lose their margins (by hitting enter multiple times).
const btn = document.querySelector('div.box');
btn.addEventListener('keypress', event => {
if (event.key === 'Enter') {
const box = document.createElement('div');
box.className = 'box';
document.body.appendChild(box);
}
});
* {
margin: 0;
padding: 0;
}
div.box {
width: 100px;
height: 40px;
background: red;
display: inline-block;
}
<div tabindex="1" class='box'></div>
Can anyone explain why there is a discrepancy in how these dynamically added div
elements are rendered compared to statically coded ones? Is there an issue with the JavaScript implementation?