To place the ball in the middle of the field element, I need to divide its size by 2, but I cannot divide its size by two, because for some reason it is impossible to get its width and height in any way. How are the pictures of the element in the example below correctly getting offsetWidth / Height?
let ball = document.getElementById('ball'); let field = document.getElementById('field') console.log(ball.offsetWidth); -> ВЫВОДИТ 0 почему-то ball.style.left = document.body.children[0].clientWidth / 2 + "px" full example
let ball = document.getElementById('ball'); let field = document.getElementById('field') console.log(ball.offsetWidth); ball.style.left = document.body.children[0].clientWidth / 2 + "px" #field { width: 200px; border: 10px groove black; background-color: #00FF00; position: relative; } #ball { position: absolute; } <div id="field"> <img src="https://js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . </div>