开发者

How to center the image of unknown size inside div?

Assume that I have a div having the following styles:

#container {
    position: fixed;
    width: 100%;
    heigh开发者_JAVA技巧t: 100%;
}

Also I have an image of unknown size (the size may vary), which I want to align both vertically and horizontally.

What is the best way of doing that?


The background image method will work, with background-position:center center, unfortunately you'll lose control of scaling your image.

You can set your image as follows:

position:absolute;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;

PS. Keep in mind that this will be centered relative to its closest positioned parent.


Add the following:

The first two lines center it vertically, the last horizontally.

display: table-cell;
vertical-align: middle ;
text-align: center;

more info can be found here: http://www.w3.org/Style/Examples/007/center


The easiest cross-browser way would be to set your dynamic image as a background property on the #container:

<div id="container" style="background: url(path/to/image.png) no-repeat 50% 50%"></div>


This will center vertically and horizontally.

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

http://jsfiddle.net/nfBDT/


i believe the easiest way is to do this:

.container img {
    display:block;
    margin:auto;
}

adjust .container to suit your div (not sure if yours was a class or ID)

oh I didn't read all of your question.

this appears to work:

<style type="text/css">
.wraptocenter {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: ...;
    height: ...;
}
.wraptocenter * {
    vertical-align: middle;
}
/*\*//*/
.wraptocenter {
    display: block;
}
.wraptocenter span {
    display: inline-block;
    height: 100%;
    width: 1px;
}
/**/
</style>
<!--[if lt IE 8]><style>
.wraptocenter span {
    display: inline-block;
    height: 100%;
}
</style><![endif]-->

full credit: http://www.brunildo.org/test/img_center.html


http://zoffix.com/new/absolute-center-random-width-height.html

This is a pretty decent example. Usually you use table/vertical-align for modern browsers and positioning+%s for IE.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜