I have a bunch of the same divs whose display property is set to inline-block. I know that inline-block elements have, by default, some margin around them so without any modification, I would expect some free space surrounding these elements (this question is not about removing them).
If I simply hard-code them into html file, then they behave as I expect them to.
* {
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>
But if I start adding them via JavaScript, the top and bottom margins stays the same, but left and right seems to disappear.
In this code, if I tab into the first element and then hit enter, the new div is created and added into DOM but as mentioned above, margins are gone when I start adding more of them (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>
Anyone knows why there is a difference in how these divs are rendered when hard-coded vs added programmatically? Is there something wrong with the JavaScript code?