我有一個照片目錄,其中大部分的縱橫比為 4:3。有一些奇怪的,將它們裁剪為 4:3 而不丟失圖片的重要部分是不可行的。
我想在每張照片的相同尺寸的邊界框中顯示所有這些照片,包括少數奇數尺寸的照片。邊界框由div類的 a 確定col-md-4:
<div class="row">
<div class="col-md-4">
<!- the image here: -->
<img class="img img-responsive" src=" ... " />
</div>
<div class="col-md-8">
<!- other stuff -->
</div>
</div>
對于那些已經是 4:3 的影像,它們都以完全相同的顯示尺寸很好地顯示出來,即使影像(檔案)大小可能不同,例如一個可以是 1024x768,另一個是 800x600。
對于“太寬”的影像,我希望它顯示為(其中灰色條代表邊界區域的背景):

對于“太高”的影像,我希望它顯示為:

In other words, each odd size image should "choose" its height or width to fit into the bounding box depending on whether it is too tall or too fat. Is this achievable by bootstrap and css?
It may be worthwhile noting that currently, the bounding div has the same width set by bootstrap for every image. The height is determined by the image's aspect ratio. When every photo is at 4:3, then the heights are also all the same. So for odd-size photos, the height has to be locked at 3/4 of the display width.
uj5u.com熱心網友回復:
您可以使用 padding-top 和絕對定位(以及一些魔法)來實作:
.imagewrapper {
display: block;
position: relative;
background-color: blue;
border: 1px solid red;
}
.imagewrapper:before {
content: '';
display: block;
width: 100%;
/* this is AR of 16:9 calculated 9:16*100 = 56.25 */
padding-top: 56.25%;
}
.imagewrapper img {
position: absolute;
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="imagewrapper">
<img src="https://dummyimage.com/1000x200/000/fff" alt="600x400" />
</div>
<div class="imagewrapper">
<img src="https://dummyimage.com/600x400/000/fff" alt="600x400" />
</div>
<div class="imagewrapper">
<img src="https://dummyimage.com/400x600/000/fff" alt="600x400" />
</div>
如果您需要在容器另一寬高比改變padding-top的值.imagewrapper:before。它可以通過height / width * 100(例如9 / 16 * 100 = 56.25對于 16:6 或4 / 3 * 100 = 133對于 3:4)來計算。
這是如何運作的?
的before元素獲得其父的100%的寬度和特定的基于百分比的padding-top值(例如56.25%),這使得它采取其寬度為高度基本上使它固定AR盒的56.25%。
影像通過絕對位置、頂部、左側和變換在此框內居中定位,而其大小由高度和寬度自動包含,但最大高度和最大寬度為 100%。
你可以把它放在任何改變外部元素寬度的東西里面,它應該可以作業。
使用可以實作類似的行為,aspect-ratio但此解決方案適用于 MSIE 和其他(舊版)瀏覽器,并且基本上也適用于本世紀以來的所有內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/322360.html
標籤:css twitter-bootstrap bootstrap-4 responsive-images
上一篇:如何使用document.querySelector選擇我的CSS模塊類?
下一篇:放大旋轉木馬的第一張幻燈片
