I am trying to center a span inside a paragraph using JavaScript. This is my code :
document.addEventListener('DOMContentLoaded', () => {
window.onload = function(){middle();}
var titleHeight = document.getElementById("page-title").clientHeight;
var titleWidth = document.getElementById("page-title").clientWidth;
var objHeight = document.getElementById("head-text").clientHeight;
var objWidth = document.getElementById("head-text").clientHeight;
var moveit = document.getElementById("head-text");
var moveit = document.getElementById("head-text");
function middle(){
console.log(titleHeight/2-objHeight/2);
moveit.style.top=titleHeight/2-objHeight/2;
moveit.style.left=titleWidth/2-objWidth/2);
}
})
It always returns undefined for the titleHeight.How do I solve this?
I tried centering the element by css but that doesn’t help.So I had to switch to JavaScript. I need any possible was by JavaScript to position my element.
2
Answers
You really should do this with CSS, but in JS you need to call
element.getBoundingClientRect()
to get accurate positional information.Also, you’re setting
objWidth
toclientHeight
.It’s quite slow and will cause jank, but…
Might bee problematic because span is default inline html. Try to set css and define it as inline-block, before the javascript manipulation: