par par - 20 days ago 7
Javascript Question

Why is my precision web layout imprecise?

I am having a problem modifying HTML with Javascript. An example can be found here: https://jsfiddle.net/02mwyvyo/

My goal is to move a specific element down the page. I am trying to do this by inserting a spacer

div
before the target element. The spacer
div
's style attributes are
style="display: inline-block; width=1px; height=100px;"
.

Here is the code I am using:

function describeDOMRect(rect) {
return "{ top: " + rect.top + ", left: " + rect.left + ", bottom: " + rect.bottom + ", right: " + rect.right + " }"
}

function addVerticalSpacer() {
var div = document.getElementsByClassName("target-div")[0]
var bounds = div.getBoundingClientRect()

console.log("old bounds: " + describeDOMRect(bounds))

var spacerHeight = 100
var newTop = bounds.top + spacerHeight
var spacer = document.createElement("div")

spacer.className = "spacer"
spacer.setAttribute("style", "display: inline-block; width: 1px; height: " + spacerHeight + "px;")

div.parentNode.insertBefore(spacer, div)

bounds = div.getBoundingClientRect()

console.log("new bounds: " + describeDOMRect(bounds))
}


And here are the CSS properties applied to
div
:

div {
border: none;
border-width: 0;
padding: 0;
margin: 0;
}


When I run the code above, this is what I see in the console:

old bounds: { top: 26, left: 8, bottom: 26, right: 729 }
new bounds: { top: 112, left: 8, bottom: 112, right: 729 }


Notice the old top position is 26, so I expect the new top to be 126, but it is 112.

Why is this happening? What can I do to correct it?

Answer

You are actually inserting the spacer div between Some text and Some more text. Since it is an inline-block it is appended at the end of the first line.

enter image description here