我的问题比标题说得复杂一点。对不起,我不知道如何更具体...复杂的CSS图像居中帮助?
我正在一个网站上,我遇到了一个部分,我应该显示一些缩略图。事情是,缩略图的尺寸不匹配。 (我知道,这听起来很可笑,因为这是缩略图,对吧?)不,没有办法在相同的尺寸下创建它们!我已经设法创建了一个HTML + CSS结构来解决这个问题,并且如果图像尺寸较小而且保持纵横比不变,则图像不会伸展以适合它们的容器。
剩下的唯一问题是将图像居中。由于将边距设置为“0 auto”或“auto 0”没有帮助,因此我尝试设置multiple containers and setting the margins来定位图像。这也不起作用:如果我将120x120图片放入120x80内部容器中,并将容器的顶部和左侧边距设置为-50%,则边距将变为-60px。这可以解决吗?还是有另一种方法来中心图像?
我愿意接受任何建议!
HTML:
<div id="roll">
<div class="imgfix">
<div class="outer">
<div class="inner">
@if (ImageDimensionHelper.WhereToAlignImg(item.Width, item.Height, 120, 82) == ImgAlign.Width)
<!-- ImageDimensionHelper tells me if the image should fit the
container with its width or height. I set the class of the img
accordingly. -->
{
<img class="width" src="@Url.Content(item.URL)" alt="@item.Name"/>
}
else
{
<img class="height" src="@Url.Content(item.URL)" alt="@item.Name"/>
}
</div>
</div>
</div>
</div>
CSS:
.imgfix{ overflow:hidden; }
.imgfix .outer { width:100%; height:100%;}
.imgfix .inner { width:100%; height:100%; margin-top:-50%; margin-left:-50%; }
/*This div (.inner) gets -60px for both margins every time, regardless of the size of itself, or the image inside it*/
#roll .imgfix { width:120px; height:82px; border: 1px #5b91ba solid; }
#roll .imgfix .outer { margin-top:41px; margin-left:60px; }
/*since I know specificly what these margins should be, I set them explicitly, because 50% got the wrong size.*/
#roll .imgfix img.width { width:120px; height:auto; margin: auto 0; }
#roll .imgfix img.height { height:82px; width:auto; margin: 0 auto; }
请出示你的代码 – sandeep
做你想要做一个纯CSS居中或者是你不反对用js来做到这一点?我可以为您提供一个jQuery解决方案(也许尺寸插件扩展) –
我只想尽可能地坚持CSS。 – Tenshiko