Grow your CSS skills. Land your dream job.

CSS Centering Images help

  • # May 20, 2012 at 7:31 pm

    Need a bit of help, I have two images here they are centering but I’m trying to get them besides each other. Heres what I have.

    .img {

    margin-left: auto;
    margin-right: auto;
    width: 8em;



    }

    And the HTML…








    # May 20, 2012 at 7:43 pm

    Replace:

    .img {
    margin-left: auto;
    margin-right: auto;
    width: 8em;
    }

    with:

    .img {
    text-align: center;
    }​

    Then, if you want to adjust their vertical alignment, you can do so with the vertical-align property:

    .img img {
    vertical-align: middle; /* bottom, top, or any of the other options */
    }
    # May 20, 2012 at 9:00 pm

    @joshuanhibbert Question: What about when you have an unknown height and width and want to set an image vertically/horizontally center dynamically?

    I apologize for the hijack

    # May 20, 2012 at 9:05 pm

    @ChristopherBurton I generally use one of the techniques here: http://css-tricks.com/centering-in-the-unknown/

    The upside is that you don’t need to use any extra markup, the downside is that it won’t work in IE7.

    # May 20, 2012 at 9:19 pm

    @joshuanhibbert Thanks. Too bad I need a jQuery solution.

    I found this

    jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) +
    $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) +
    $(window).scrollLeft() + "px");
    return this;
    }

    // Now we can just write:

    $(element).center();

    Solved: Result

    # May 20, 2012 at 9:47 pm

    Ah, right. I did something similar a while ago that might be worth looking at: http://jsfiddle.net/joshnh/Ff5hm/

    It’s not as flexible as what you are currently using, but it is less code for a single image.

    # May 20, 2012 at 10:00 pm

    @joshuanhibbert Actually that worked perfect. Thanks again.

    # May 20, 2012 at 10:11 pm

    @ChristopherBurton No worries!

    # May 21, 2012 at 12:35 pm

    Thank you for the quick help and reply!

    # May 21, 2012 at 12:47 pm

    How about this? No js needed. Moves re-centers dynamically when re-sized.
    http://jsfiddle.net/joshnh/Ff5hm/

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

You must be logged in to reply to this topic.

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