我想将未知宽度/高度的图像居中放置在页面上,同时确保它比页面大时缩小(即使用max-width/ max-height)。
我尝试使用该display:table-cell方法,但max-width在 Firefox 中对于使用display:table-cell. 有没有办法在不使用的情况下垂直居中可变高度元素display:table-cell?
我可以更改标记。JavaScript 是可以接受的,但我不能使用 JQuery(或任何其他 JS 库)。
我想将未知宽度/高度的图像居中放置在页面上,同时确保它比页面大时缩小(即使用max-width/ max-height)。
我尝试使用该display:table-cell方法,但max-width在 Firefox 中对于使用display:table-cell. 有没有办法在不使用的情况下垂直居中可变高度元素display:table-cell?
我可以更改标记。JavaScript 是可以接受的,但我不能使用 JQuery(或任何其他 JS 库)。
这应该证明工作得很好......不需要JavaScript :)
请参阅jsFiddle 上的工作演示。
/* 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%;
}
<img class="absoluteCenter" src="PATHTOIMAGE">
注意:这个类可以很容易地用于任何事情。如果您将其用于图像以外的其他内容,请确保添加TAG.absoluteCenter带有您选择的max-height和max-width的CSS 规则(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>