开发者

how to center img vertically and horizontally in a container - img may potentially be larger than container

开发者 https://www.devze.com 2023-04-08 09:12 出处:网络
I have a container that will contain an image, and this image is loaded from an application and so the dimensions of the container is known while the image will vary.

I have a container that will contain an image, and this image is loaded from an application and so the dimensions of the container is known while the image will vary.

I currently have the following 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 
}

This works 'okay' form me: it loads the image, resizes it to take up 100% of the container's width and positions it so that the bottom-half of the image is displayed within the container - so if the image ends up being 200px high after resizing the width to 300px, only the bottom 100px of the image is displayed (an arbitrary setting).

What I'm trying to do is to always display the middle of the image - so 开发者_如何学Goin the example above, the image would display pixels 50-150 (from the top)..


Since it sounds like you don't know the image size on page load, you could use a combination of dead centre and javascript to do what you want. The flow would be as follows:

  1. Setup markup as in the dead centre example.
  2. When image is loaded, get its width and height.
  3. Set image margin-left to (image width / 2 * -1).
  4. Set image top to (image height / 2 * -1).

Since you may also have images that are larger than your container, you could add a conditional check for this:

// 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";
  }
}
0

精彩评论

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

关注公众号