开发者

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

开发者 https://www.devze.com 2023-02-27 09:17 出处:网络
Is there any way? Using Javascript/JQuery? I really really really need it. Any help is appr开发者_高级运维eciated.Don\'t use JavaScript when you aren\'t required to....

Is there any way? Using Javascript/JQuery? I really really really need it. Any help is appr开发者_高级运维eciated.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号