Search code examples
cssimagehtmlalignmentcenter

Centre Image in DIV (Original can be bigger than DIV)


Struggling with the dreaded centring of different sized images in a DIV.

Got a solution from StackOverflow ( How to vertically align an image inside div ), using a <SPAN> as a dummy element (with vertical-align: middle) and it works well except for the images which are bigger than the DIV and these are correctly resized, but shown below the DIV.

If I remove the <SPAN>, then the centring works in the horizontal, but not in the vertical.

If there is a simple change, I can make as I like the simplicity of the solution.

The tests are at

http://mclportal.net/ModalTests.html


Solution

  • This will work for you:

    <div id="divModal" style="display:table">
       <div id="divImage" style="display:table-cell; vertical-align:middle">
          <img id="img" src=".........">
       </div>
    </div>