The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Absolute center an image issue

  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
  • #44097

    Hi Everyone,

    I am currently working on a new website,
    and i have some issues with my js code.

    I would like to **center verticaly and horizontaly** an image inside a div.
    I don’t know the size of the images (images will be retrieved from a json file)

    Here is my js code :

    You can see the result here :

    The code sometime works, but when you reload the page,
    the code doesn’t work, so my images are out of their div.

    Can someone help me please ? :)

    I’m sorry for my poor english,



    The part of the JS where it sets the margin always sets it to 0. You can try to either set width and height on the img if that data is available in the JSON object, or wait till the image is loaded before running the script. Something like:

    $(‘.partenaires’).find(‘img’).each(function() {
    $(this).load(function() {
    var $this = $(this),
    widthImg = $this.width(),
    heightImg = $this.height();
    ‘left’: ‘160px’,
    ‘margin-top’: -heightImg/2

    EDIT: load is deprecated, something like `.bind(‘load’, function() { … });` would work though.


    Actually, I think that doesn’t work right because I had to trigger the event to make it work here manually, but it’s worth a shot :)


    you don’t need js at all. simply remove all the positioning and margins from the images, set the containing div to text-align: center (as you have), give a line-height equal to the height (160px) and keep the vertical-align: middle on the image.


    That’s awesome :P


    Indeed, easy, clever and awesome tricks !

    Thank you very much Wolfcry911 and CrocoDillon !

Viewing 6 posts - 1 through 6 (of 6 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.