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

时间:2011-06-08 17:42:25

标签: javascript css vertical-alignment

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

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

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

3 个答案:

答案 0 :(得分:17)

这应该证明工作得很好......没有必要的JavaScript :))

请参阅working demo on 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.absoluteCentermax-height添加max-width CSS规则(其中TAG是HTML标记您正在使用[例如div.absoluteCenter]而max-width / max-height小于100%

答案 1 :(得分:0)

尝试这样的事情......

演示: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来测试不同的尺寸。)

答案 2 :(得分:0)

这是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>​
相关问题