2016-01-28 19 views
2

這段簡單的代碼在WebKit瀏覽器中效果很好,但在IE和Firefox中失敗。我需要將img標籤用於其他功能,因此background-image不是一個選項。使用max-height,width自動約束div內的img

片段

img { 
 
    max-width: 100%; 
 
    height: auto; 
 
} 
 
.vgp-dtable { 
 
    width: 100%; 
 
    max-width: 860px; 
 
    margin: 0 auto 1em; 
 
    display: table; 
 
} 
 
.vgp-dtable .row { 
 
    display: table-row; 
 
} 
 
.vgp-dtable .row .art, 
 
.vgp-dtable .row .txt { 
 
    display: table-cell; 
 
    vertical-align: top; 
 
} 
 
.vgp-dtable .row .art { 
 
    width: 30%; 
 
    text-align: right; 
 
} 
 
.vgp-dtable .row .art img { 
 
    width: auto; 
 
    max-height: 280px; 
 
} 
 
.vgp-dtable .row .txt { 
 
    width: 70%; 
 
    text-align: left; 
 
    padding-left: 8px; 
 
}
<div class="vgp-dtable"> 
 
    <div class="row"> 
 
    <div class="art"> 
 
     <img src="http://vgpavilion.com/mags/1982/12/vg/ads/003-004-005_tn.jpg"> 
 
    </div> 
 
    <div class="txt"> 
 
     <p>Here's some sample text.</p> 
 
    </div> 
 
    </div> 
 
    <a id="riddle-of-the-sphinx"></a> 
 
    <div class="row"> 
 
    <div class="art"> 
 
     <img src="http://vgpavilion.com/mags/1982/12/vg/thumbs/007.jpg"> 
 
    </div> 
 
    <div class="txt"> 
 
     <p>Here's some sample text.</p> 
 
    </div> 
 
    </div> 
 
</div>

在WebKit的圖像適當地調整具有280像素的最大height以適應30%的寬的容器塊。然而,在Firefox和IE中,只有max-height受到尊重,圖像強制它們的容器變得比30%寬。

一個簡單的例子here。簡單的例子有一個工作版本,在破壞的display:table實現之上使用float方法。

你可以看到完整的網頁here

我已經嘗試了多個容器的組合和圖像將永遠尊重width,除非在絕對數量在Firefox或IE時指定。在之前的例子中,我使用了可在所有測試過的瀏覽器中運行的background-image解決方案,但實際上並不想這麼做。我發現一個解決方案,使用float而不是display: table-cell,但它讓我感到困惑,它在IE和Firefox中使用幾乎相同的table方法破壞,所以也許有人會發現我失蹤或我不應該添加的東西。

+0

嘗試添加溢出:隱藏;到.art或img?它導致元素像float一樣崩潰。 – seahorsepip

回答

1

只需添加table-layout:fixed這裏:

.vgp-dtable { 
    width: 100%; 
    max-width: 860px; 
    margin: 0 auto 1em; 
    display: table; 
    table-layout: fixed /*added*/ 
}