我的問題比標題說得複雜一點。對不起,我不知道如何更具體...複雜的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