1

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?

0

1 Answer 1

6

You're confusing white space with margins. Inline elements are sensitive to white space in your code, so when you generate them via JS, that whitespace doesn't exist unless you manually add it. The easiest way to see this is in your first example by putting all your divs on the same line with no spaces or carriage returns.

* {
  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>

Sign up to request clarification or add additional context in comments.

2 Comments

And conversely, if you append a document.createText("\n") between each box, you’ll see the same result as in the HTML.
Thanks both of you, I haven't thought about it like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.