将图像对齐到较小的div中心 [英] Aligning image to center inside a smaller div
问题描述
我有一个div宽度:100px和高度:100px(说)
里面,只有一个图像,其高度总是固定为100px。
我想让图像水平居中。
这里有3种情况:
<
我希望图片的中心部分在div内可见。 / p>
意味着,如果图像的宽度是120px ..和div的宽度是100px和overflow:hidden
我想要图像的第10个px到第110个px是可见的,
这是可能通过一些CSS属性吗?
我不知道加载的图像的宽度!所以我想它是动态的。
也想避免javascript边计算找到额外的宽度和给左边距:-ve值bla bla .. )
此外,我无法将图片作为div的背景图片。
查看: http://jsfiddle.net/thirtydot/x62nV/(和无 overflow:hidden
即可轻松查看
$ c> .imageContainer> span , margin-left
源自 width
$ c> width 是控制将支持的最大图像宽度的任意数字。你可以设置 width:10000px;
< div class =imageContainer>
< span>< img src =http://dummyimage.com/100x100/f0f/fff/>< / span>
< / div>
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;
}
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.
I want to make the image horizontally center.
Here there are 3 cases:
- image's width is equal to div's width, no issues
- image's width is less than div's width, I can use margin: auto here
- image's width is more than div's width
I want the center part of the image to be visible inside the 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 )
Is this possible through some CSS property? (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.. )
Also, I can't give the image as background-image for the div!
See: http://jsfiddle.net/thirtydot/x62nV/ (and without overflow: hidden
to easily see the centering)
This will work in all browsers, with the possible exception of 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. You could set width: 10000px; margin-left: -4950px;
to support really wide images, if required.
HTML:
<div class="imageContainer">
<span><img src="http://dummyimage.com/100x100/f0f/fff" /></span>
</div>
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;
}
这篇关于将图像对齐到较小的div中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!