2011-09-26 60 views
1

我有一个包含图像的容器,并且此图像是从应用程序加载的,因此容器的尺寸是已知的图像会有所不同。如何在容器中垂直和水平居中放置img - img可能会大于容器

我现在有下面的CSS:

#secondary_photos { 
    height: 100px; 
    width: 300px; 
    overflow: hidden; 
} 

#secondary_photos .small_photo { 
    float:left; 
    height: 100px; 
    width: 300px; 
} 

#secondary_photos .small_photo img{ 
    height: 100%; 
    width: auto; 
    position: absolute; 
    bottom: 0px 
} 

#secondary_photos .small_photo img{ 
    height: auto; 
    width: 100%; 
    position: absolute; 
    bottom: 0px 
} 

这个工程“没关系”形成了我:它加载图像,调整其大小,以占据容器的宽度的100%,其位置,以便自下而上图像的一半显示在容器内 - 因此,如果在将宽度调整为300像素后图像的高度为200px,则只显示图像的底部100px(任意设置)。

我试图做的是始终显示图像的中间 - 所以在上面的例子中,图像将显示像素50-150(从上往下)..

回答

1

因为它听起来像你不知道页面加载时的图片大小,你可以使用dead centre和javascript的组合来做你想做的事。流程如下:

  1. 设置标记为死中心示例。
  2. 加载图像时,获取其宽度和高度。
  3. 将图片边距设置为(image width/2 * -1)
  4. 设置图像顶部到(image height/2 * -1)

既然你也可能有比你的大容器的图像,你可以添加一个条件检查此:

// Get DOM elements 
var container = document.getElementById('container'); 
var image = document.getElementById('img'); 

// Check they're good 
if(container && img){ 
    var height = image.height; 
    var width = image.width; 

    // Horizontally centre if container is wider than image 
    if(container.offsetWidth > width){ 
    image.style.marginLeft = Math.floor((width/2 * -1)) + "px"; 
    } 

    // Vertically centre if container is taller than image 
    if(container.offsetHeight > height){ 
    image.style.top = Math.floor((height/2 * -1)) + "px"; 
    } 
}