Center a div using javascript?

I am currently trying to center a rectangle in an image with only using javascript (no css center properties). However, even if the numbers are right, the showing is wrong.
To do this, I use the following code :

$(document).ready(function() {
    
    $(".img-zoom-container").css("width", $("#myimage").width());
    $(".img-zoom-container").css("height", $("#myimage").height());
    
    $("#lens_container").css("width", ($("#myimage").width() - $("#lens").width()));
    $("#lens_container").css("height", ($("#myimage").height() - $("#lens").height()));
    $("#lens_container").css("top", ($("#lens").height() / 2));
    $("#lens_container").css("left", ($("#lens").width() / 2));
    
});
.img-zoom-container
{
    border: 1px solid red;
}

#lens
{
    border: 1px solid white;
    width: 50px;
    height: 50px;
    position: absolute;
}

#lens_container
{
    border: 1px solid cyan;
    position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="img-zoom-container">
    <div id="lens"></div>
    <div id="lens_container"></div>
    <img id="myimage" src="https://via.placeholder.com/600x160.png?text=Testing Image" alt="">
</div>

The item I am trying to center is the #lens_container div (appears blue on screen). I also have a white square (#lens div) of size 50px by 50px. I would like to center and to size the blue rectangle in order to have half of the square width at each side of the blue rectangle and same with height. However, as you can see when trying the code, it is not the case although the maths are correct.

I do not know if you can understand my needs, but I would really appreciate help there.

Thanks in advance.

102 thoughts on “Center a div using javascript?”

Leave a Comment