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


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


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

    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 = function () {
    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:


    Solved: Result

    # May 20, 2012 at 9:47 pm

    Ah, right. I did something similar a while ago that might be worth looking at:

    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.

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

You must be logged in to reply to this topic.