简体   繁体   English

将图像对齐到较小div内的中心

[英]Aligning image to center inside a smaller div

I have a div with width:100px and height:100px (say) Inside that, there is just an image, for which height is always fixed to 100px . 我有一个width:100px为div的div width:100pxheight:100px (比如)里面只有一个图像,其高度始终固定为100px

I want to make the image horizontally center. 我想让图像水平居中。

Here there are 3 cases: 这里有3个案例:

  1. image's width is equal to div's width, no issues 图像的宽度等于div的宽度,没有问题
  2. image's width is less than div's width, I can use margin: auto here 图像的宽度小于div的宽度,我可以使用margin: auto here
  3. image's width is more than div's width 图像的宽度大于div的宽度

I want the center part of the image to be visible inside the div. 我希望图像的中心部分在div中可见。

means, if image's width is 120px and as div's width is 100px and overflow:hidden I want image's 10th px to 110th px to be visible (so, the left: 10px and right: 10px of image are hidden under the div ) 意味着,如果图像的宽度是120px并且div的宽度是100px并且overflow:hidden我想要图像的第10个px到第110个px是可见的(所以, left: 10pxright: 10px的图像隐藏在div下面)

Is this possible through some CSS property? 这可能通过一些CSS属性吗? (I dont know the width of image which is loading! so I want it to be dynamic. Also want to avoid javascript side calculations to find the extra amount of width and giving margin-left: -ve value bla bla.. ) (我不知道正在加载的图像的宽度!所以我希望它是动态的。还想避免javascript端计算找到额外的宽度并给出margin-left: -ve value bla bla ..)

Also, I can't give the image as background-image for the div! 另外,我不能将图像作为div的background-image

See: http://jsfiddle.net/thirtydot/x62nV/ (and without overflow: hidden to easily see the centering) 请参阅: http //jsfiddle.net/thirtydot/x62nV/ (并且没有overflow: hidden以轻松查看居中)

This will work in all browsers, with the possible exception of IE6. 这适用于所有浏览器,可能除了IE6。

For .imageContainer > span , the margin-left is derived from the width , and the width is an arbitrary number which controls the maximal image width that will be supported. 对于.imageContainer > spanmargin-leftwidth派生, width是一个任意数字,用于控制将支持的最大图像宽度。 You could set width: 10000px; margin-left: -4950px; 你可以设置width: 10000px; margin-left: -4950px; width: 10000px; margin-left: -4950px; to support really wide images, if required. 如果需要,支持真正的宽图像。

HTML: HTML:

<div class="imageContainer">
    <span><img src="http://dummyimage.com/100x100/f0f/fff" /></span>
</div>

CSS: CSS:

.imageContainer {
    border: 1px solid #444;
    overflow: hidden;
    width: 100px;
    height: 100px;
    margin: 15px;
    text-align: center;
}
.imageContainer > span {
    display: block;
    width: 1000px;
    margin-left: -450px; /* -(width-container width)/2 */
}
.imageContainer > span > img {
    display: inline-block;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM