[英]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:100px
和height:100px
(比如)里面只有一个图像,其高度始终固定为100px
。
I want to make the image horizontally center. 我想让图像水平居中。
Here there are 3 cases: 这里有3个案例:
margin: auto
here margin: auto
here 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: 10px
和right: 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 > span
, margin-left
从width
派生, 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.