The sporadic nature of inline-block elements' behavior when generated through JavaScript

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?

Answer №1

There is a common misconception between white space and margins when it comes to inline elements. White space plays a significant role with inline elements in your code, as they are sensitive to it. When generating inline elements through JavaScript, the absence of white space may not be noticeable unless manually added. The best way to observe this is by placing all your divs in a single line without any spaces or line breaks.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``I am experiencing an issue with HttpXMLRequest becoming un

I am currently experimenting with the HttpXMLRequest object in JS and have created a basic loop that retrieves name and age data from an XML file to display in a table. The issue I am facing is that if one of the elements is missing from a sibling, the cod ...

Event triggered by input, change, keyup, or focus not activated

Here is the function I am working with: displayReviews: function(){ var main = document.getElementById("main"); var inputs = main.getElementsByTagName("INPUT"); var isVisible = $("reviewcontent& ...

The function does not get activated when mouseover event is triggered with AddEventListener

I am attempting to create a series of radio buttons, each with its own AddEventListener function. However, I am encountering issues while using the code below within a while loop that retrieves data from a MySQLI table: echo ' <script> do ...

Customize the <td> column based on values and rows. Modify the current jQuery code

This code snippet contains an HTML table that dynamically populates based on the dropdown selection. The script included in the code highlights the best and worst values in the table by changing their background color to green and red, respectively. & ...

I'm trying to implement a command in my bot that displays the number of Discord members, but I keep encountering an error

I've encountered an issue with the discord.js v13 member count command. Despite seeking help in various Discord servers, I haven't received any assistance. If anyone could offer their expertise, it would be greatly appreciated. const Discord = re ...

Finding the next div by its ID using jQuery

Currently, the jQuery code provided only allows navigation from the Sport section to the Entertainment section. Is there a way to create a script that allows navigation between any div sections with just one piece of code? <div id="topBar"> &l ...

I encountered a response error code 500 from the development server while using my emulator

As I embark on setting up the react-native environment for development, I encounter an error when executing the command react-native run-android. root@pc:~/l3/s2/DevMobMultipltm/Wakapp# ` A series of tasks are carried out including scanning folders for sy ...

"What is the best way to store the last three lines of text from a textarea into three separate variables

I am working with an HTML file that contains a textarea tag. My goal is to copy and paste text with multiple lines into the textarea and then use JavaScript to extract the last three lines into three separate variables. The textarea has the id "txt" a ...

<a> slightly off-centered horizontal alignment

I've been trying to center a link using different methods like text-align:center and display:inline-block, but it seems to be slightly off-center. I've attached images along with my code below for reference. Any assistance would be greatly apprec ...

Align the h2 header vertically within a div container

So, here's the HTML structure that I'm working with: <div class="category"> <div class="container bottom"> <h2>Name1</h2> </div> <div class="container top"> <h2>Name2</h2&g ...

Chrome browser exhibits a phenomenon where the Bootstrap modal will erroneously print the same page multiple times based on the

When I open a modal, there's a print button inside it. I've researched solutions provided here and here to enable printing of Bootstrap modals, but I'm encountering a Chrome-specific bug. The issue doesn't occur in Safari, Firefox, or E ...

How can attributes be passed to a Vue JS computed property getter and setter?

Attempting to utilize computed properties for binding input fields with the Vuex Store has presented some challenges. Each Data Stream in my application has dynamic input fields, managed through the admin section. I need to allow users to select a specific ...

capture the alteration of text within an input field

Currently, I am utilizing the Joomla calendar feature to select a date. The HTML code for this functionality is displayed below. When you click on the image, a calendar will pop up allowing you to choose a date. Once selected, the popup closes and the date ...

JavaScript that is subtle and lacks function parameters

Suppose you have: <div id="data" onclick="handleData(1)">Datum 1</div> and you prefer late binding instead: <div id="data">Datum 1</div> <script> $("#data").click(function() { handleData(1); }) </script&g ...

How to Alphabetize an Array of Strings Containing Numbers using TypeScript and Angular

I'm working with an array that looks like this: arr = ["100 abc", "ad", "5 star", "orange"]; The goal is to first sort the strings without numbers at the beginning, then sort the strings with numbers added at t ...

Align div in the center vertically if its height is smaller than the height of the browser window (

I'm currently utilizing CSS bootstrap 4 to create a layout with multiple columns per row inside a container. Depending on the screen size, these columns may stack on top of each other, causing the container to become taller and sometimes exceed the vi ...

Unable to programmatically modify the src attribute on embed player - experiencing issues

I have been attempting to modify the src attribute in order to play a YouTube video using JavaScript, but so far I haven't had any success. Here is the code snippet I've been trying to use: $("#youtube-player").setAttribute('src', obj ...

Switching Background Colors with CSS

Can you change background colors using only CSS3? I attempted to use keyframe animations, but they only transition the background color. I simply want the background color to change after 5 seconds with no transition or hover effects. If I can fade it in ...

Purge POST request cache in Node.js

Currently, I have implemented nodemailer to enable users to contact me via email. Once the form data is submitted successfully, the page redirects to my homepage as intended. However, if an attempt is made to refresh the page, a confirmation alert pops up ...

Uncovering the secrets of accessing req.body through expressjs

I'm having trouble accessing the body when receiving an expressjs request Here is my main server.js file: app.use(express.urlencoded({extended: true})); app.use(express.json()); app.use(router); And this is my router.js file: ...