开发者

centering image vertically in all resolutions

开发者 https://www.devze.com 2022-12-29 02:24 出处:网络
I need to be able to center the image vertically for all the common resolutions. A lot of ppl here on SO have already asked this question before, and 90% of then give this tutorial

I need to be able to center the image vertically for all the common resolutions. A lot of ppl here on SO have already asked this question before, and 90% of then give this tutorial http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

as an answer. However, when viewed at my 1280 by 10开发者_JAVA百科24 res monitor in FF, it's not centered. And worse yet, it breaks horribly in IE7. So, it's definitely NOT the answer.

Am I chasing the impossible dream? The solution has to work for FF and IE 6/7

the solution can be anything that would work, though being a bit of a purist, I would prefer a div over table:)

specifically i need it for this site http://www.codecookery.com/test/index.html

as you see, it's a slideshow, that needs to be centered.


I believe this solution is what you're looking for. I don't have access to IE to test it (that's what I get for using Linux), but I'm fairly confident it works. And in regards to a div over a table, how about no wrapper at all? Not only that, but if the image is larger than the resolution of the monitor, it will scale down quite nicely. You can adjust the max-height and max-width if you want a little padding along the edges (for extremely large images and/or small resolutions).

The CSS:

<style>

/* Positioning */
.absoluteCenter {
 margin:auto; /* Required */
 position:absolute; /* Required */
 top:0;bottom:0; /* Aligns Vertically - Remove for Horizontal Only */
 left:0;right:0; /* Aligns Horizontally - Remove for Vertical Only  */
}

/* Sizing */
.absoluteCenter { /* Fallback */
 max-height:100%;
 max-width:100%;
}

</style>

And the HTML:

<img class="absoluteCenter" src="PATHTOIMAGE">

Notes:

  • Images will keep Aspect Ratio


If a fixed-height div is an option then you can use position absolute with top 50% and then use a negative margin to position the div. I tested the following in FF3.6, IE6, IE8 and Chrome.

<html>
<head>
  <style>
    #vertCenter {
        height: 400px; 
        position: absolute; 
        top: 50%; 
        margin-top: -200px;
        border: 1px green solid;
    }
  </style>
</head>

<body>
  <div id="vertCenter">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
  </div>
</body>
</html>


The code here is less horrible than that of jakpsatweb.cz.

0

精彩评论

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

关注公众号