简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM