Reputation: 5458
I have a situation where sometimes elements are loaded at page load, and sometimes they are generated by JavaScript at a later date, nothing fancy there. However the dynamically genrated elements are spaced apart noticeably different in Chrome, FireFox, and Safari.
Below is an HTML page where one chunk of elements is in the DOM at page load and an exact copy of those elements is added by JavaScript after page load. For some reason the JS-added elements (those in #added-late
) are styled different from those in #exists-at-page-load
despite all styling and layout being the same.
Question: Why do the statically generated elements, those in #exists-at-page-load
, have extra space around them?
<!DOCTYPE html>
<html>
<style>
.dark-section-header {
background-color: #222;
margin-bottom: 5px;
}
.dark-section-header div {
display: inline-block;
height: 30px;
width: 20px;
margin: 0;
margin-left: 10px;
}
.dark-section-header .track-menu {
outline: 1px dashed #f00;
}
.dark-section-header .play-button {
outline: 1px dashed #0f0;
}
.dark-section-header .star-button {
outline: 1px dashed #77f;
}
</style>
</head>
<body>
<div id="exists-at-page-load">
<div class="dark-section-header">
<div class="play-button"></div>
<div class="track-menu"></div>
<div class="star-button"></div>
</div>
</div>
<div id="added-late"></div>
<script>
setTimeout(function(){
document.getElementById( 'added-late' ).innerHTML =
'<div class="dark-section-header">' +
'<div class="play-button"></div>' +
'<div class="track-menu"></div>' +
'<div class="star-button"></div>' +
'</div>';
}, 0 );
</script>
</body>
</html>
Upvotes: 1
Views: 51
Reputation: 1741
Because they are displayed as inline-block the line breaks are causing them to have whitespace
If I change your static divs to
<div class="play-button"></div><div class="track-menu"></div><div class="star-button"></div>
whitespace goes away
Upvotes: 2
Reputation: 97641
Either have javascript insert whitespace between the divs:
setTimeout(function(){
document.getElementById( 'added-late' ).innerHTML =
'<div class="dark-section-header"> ' +
'<div class="play-button"></div> ' +
'<div class="track-menu"></div> ' +
'<div class="star-button"></div> ' +
'</div>';
}, 0 );
Or ensure your HTML does not:
<div id="exists-at-page-load">
<div class="dark-section-header">
<div class="play-button"></div><!--
--><div class="track-menu"></div><!--
--><div class="star-button"></div>
</div>
</div>
Here's every combination of js and spacing.
Upvotes: 3