Search code examples
javascriptjquerycssimagealignment

How to vertically and horizontally align an image in a DIV without altering width/height?


Is there any way? Using Javascript/JQuery? I really really really need it. Any help is appreciated.


Solution

  • Don't use JavaScript when you aren't required to....

    Background method

    You could set it as the background...

    div {
       background: url(/path/to/img.png) no-repeat center center;
    }
    

    jsFiddle.


    position: absolute method

    Or you could position the img absolutely...

    div {
       position: relative;
    }
    
    div img {
       position: absolute;
       top: 50%;
       left: 50%;
       margin-left: -50px;
       margin-top: -50px;
    }
    

    jsFiddle.

    Where -50px is half the respected dimension of the image.


    display:table-cell and vertical-align: middle method

    You could also use vertical-align: middle.

    div {
       display: table-cell;
       vertical-align: middle;
       text-align: center;
    }
    

    jsFiddle.

    Keep in mind this won't work < IE8.

    There are even more ways to achieve this too...