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.
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
objWidthtoclientHeight.It's quite slow and will cause jank, but...