Grow your CSS skills. Land your dream job.

Absolute center an image issue

  • # April 13, 2013 at 12:28 pm

    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 : http://pastebin.com/NUhAdA7c

    You can see the result here : http://emalsaifi.com/purprodv2/partenaires.php

    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,

    Emal

    # April 13, 2013 at 12:53 pm

    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();
    $this.css({
    ‘top':’80px’,
    ‘left': ‘160px’,
    ‘margin-left':-widthImg/2,
    ‘margin-top': -heightImg/2
    });
    });
    });

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

    # April 13, 2013 at 1:11 pm

    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 :)

    http://jsfiddle.net/babUH/

    # April 13, 2013 at 4:12 pm

    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.

    # April 13, 2013 at 5:35 pm

    That’s awesome :P

    # April 14, 2013 at 1:39 pm

    Indeed, easy, clever and awesome tricks !

    Thank you very much Wolfcry911 and CrocoDillon !

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".