垂直居中可变高度图像,同时保持最大宽度/高度

Vertical centering variable height image while maintaining max-width/height

本文关键字:高度 图像 垂直居中      更新时间:2023-09-26

我想将宽度/高度未知的图像居中放置在页面上,同时确保它在大于页面时收缩(即使用max-width/max-height)。

我尝试使用display:table-cell方法,但对于用display:table-cell声明的元素中的所有元素,在Firefox中都会忽略max-width。有没有一种方法可以在不使用display:table-cell的情况下垂直居中可变高度元素?

我可以更改标记。JavaScript是可以接受的,但我不能使用JQuery(或任何其他JS库)。

这应该能很好地工作。。。无需JavaScript:)

请参阅jsFiddle上的工作演示。

CSS

/* Don't Change - Positioning */
.absoluteCenter {
 margin:auto;
 position:absolute;
 top:0;
 bottom:0;
 left:0;
 right:0;
}
/* Sizing */
img.absoluteCenter {
 max-height:100%;
 max-width:100%;
}

HTML

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

注意:这个类可以很容易地用于任何事情。如果您将其用于图像以外的其他内容,请确保添加一个TAG.absoluteCenter CSS规则,其中包含您选择的max-heightmax-width(其中TAG是您正在使用的HTML标记[例如div.absoluteCenter],max-width/max-height小于100%

试试这样的。。。

演示:http://jsfiddle.net/wdm954/jYnk8/1/

$(function() {
    h = $('.img').height();
    w = $(window).height();
    if (h < w) { 
        $('.img').css('margin-top', (w - h) /2 + "px");
    }
    else {
        $('.img').height(w);
    }
});

(您可以通过更改我注释掉的一些CSS来测试不同的大小。)

以下是javascript的一种方法:

<html>
<head>
<style>
  html, body{
    height:100%;
    margin:0;
    border:0;
    padding:0;
    background:#000;
  }
  body{
    position:relative;
  }
  img{
    border:0;
    padding:0;
    margin:0 auto;
    max-width:100%;
    max-height:100%;
    display:block;
    position:absolute;
  }
</style>
</head>
<body>
  <img />
  <script>
    (function(){
      var imgs = [
          'http://farm3.static.flickr.com/2396/2078094921_ee60c42d0f.jpg',
          'http://farm6.static.flickr.com/5242/5353846171_9169f810dc_b.jpg',
          'http://farm6.static.flickr.com/5284/5336493514_8e41696b66_b.jpg'
        ],
        img = document.getElementsByTagName('IMG')[0],
        getStyle = function(elm){
          return window.getComputedStyle ? window.getComputedStyle(elm) : elm.currentStyle;
        },
        bodyStyle = getStyle(document.body),
        toInt = function(pxSize){
          return +pxSize.replace(/px/,'');
        },
        chgImg = function(){
          img.src = imgs[i++ % imgs.length];
          img.onload = function(){
            var imgStyle = getStyle(img);
            img.style.left = ( toInt(bodyStyle.width)  - toInt(imgStyle.width) ) / 2 + 'px';
            img.style.top =  ( toInt(bodyStyle.height) - toInt(imgStyle.height) ) / 2 + 'px';
            img.onload = null;
          };
        },
        i = 0;
      chgImg();
      setInterval(chgImg, 3000);
    })();
  </script>
</body>
</html>​