2013-02-02 56 views
0

我得到一個圖像裏面div與未知寬度高度。 我想要有一個最大的圖像寬度高度 - 類似background-size: contain獲取圖像裏面的div - 高度:自動和最大高度

這裏是我的源代碼:

CSS

.box { 
    display: block; 
    position: fixed; 
    height: auto; 
    bottom: 0; 
    top: 0; 
    left: 0; 
    right: 0; 
    margin-top: 50px; 
    margin-bottom: 50px; 
    margin-right: 80px; 
    margin-left: 80px; 
    background-color: white; 
    border: solid 2px blue; 
} 

.box img { 
    max-width: 100%; 
    max-height: 100%; 
} 

HTML

<div class="box"> 
<img src="myimage.jpg"> 
</div> 

最大寬度運作良好,但最大高度不工作。

+1

我不完全理解你想達到的目標。你想讓圖片永遠在div裏面嗎?然後只是給溢出:隱藏;到.box類。另外,刪除高度:auto;來自.box類。 – pentzzsolt

+2

您只能設置寬度或高度。如果您設置寬度,高度將相應地調整。瀏覽器無法更改圖像的'widthxheight'比例。如果圖片實際上是200x800,並且您將寬度設置爲100,那麼高度將自動爲400. –

+0

[CSS:100%寬度或高度,同時保持寬高比?]可能重複(http://stackoverflow.com/questions/3751565/css-100-width-or-height-while-keeping-aspect-ratio) – easwee

回答

1

你想要的只有CSS才能實現。

有JS插件在那裏爲你做這個。尋找imgscale這是一個jQuery插件,儘管它需要一些調整,但有一個很好的基礎。

這裏是我修改的一個拷貝鏈接:http://www.dtavares.com/imgscale/js/jquey.imgscale.js

你可以稱其爲:

$(".someConainer img").imgscale({parent: '.someConainer', scale: 'fit', center: true, fade: 0});