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

Home Forums CSS Horizontally and vertically centering an image without knowing it’s measures.

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

    So, I’m trying to set up an image gallery consisting of 4 div’s / row.
    In each of these div’s there’s an image that get’s pulled out of a database.

    I would like to center these images (horizontally and vertically).
    The problem is that I don’t know the measures or more exactly the width/height ratio.

    As some of the images will be portrait and some will be landscape I can’t preset (hard code) the measures in the html.

    Anyone a suggestion?



    I can’t give you an answer, but I can provide hints! I’m 99% sure you’ll have to dig into some JavaScript/jQuery here to measure the size of the image and then apply styles to it.

    I’m just not knowledged enough in JS to explain exactly how to do that!


    But both should be avoided, I’d say. Display: table, table-row, table-cell, etc doesn’t change anything – might as well just be using tables if you’re going to do it that way.


    Hey ilias, like TheDoc says the best way to do this is with JS, or more specifically; jQuery.

    I haven’t tested it, but something like this should work:

    var rowHeight = $(this).innerHeight();
    var rowWidth = $(this).innerWidth();
    var imgHeight = $(this).find('img').height();
    var imgWidth = $(this).find('img').width();
    var topOffset = (rowHeight - imgHeight)/2;
    var leftOffset = (rowWidth - imgWidth)/2;
    $(this).css({'padding-top' : topOffset, 'padding-left' : leftOffset});

    It basically loops through each .row and applies padding accordingly to the width and height of the image inside it.

    Hope that helps,


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