【发布时间】:2011-06-29 06:39:10
【问题描述】:
我的问题比标题说的要复杂一些。抱歉,我不知道如何更具体...
我正在开发一个网站,我遇到了应该显示一些缩略图的部分。问题是,缩略图的尺寸不匹配。 (我知道,这听起来很荒谬,因为这是缩略图,对吧?)不,根本没有办法在相同的维度上创建它们!我已经设法创建了一个 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; }
【问题讨论】:
-
你是想做纯css居中还是不反对用js来做?我可以为您提供 jQuery 的解决方案(可能是维度插件扩展)
-
只要有可能,我想坚持使用 css-only。
-
也许我将不得不为此使用 js,而后备是在左上角显示图像。
-
我已经通过一个希望工作的演示改进了我的答案,该演示仅使用 CSS 来定位图像,但它确实依赖于知道生成
<img>元素的点的图像尺寸,以便添加内联 CSSmargin规则。从您的问题来看,您似乎具有这些尺寸,所以我希望它们可以以这种方式使用。
标签: css vertical-alignment alignment