2016-02-11 58 views
0

我有具有以下CSS一個div profile_pic調整圖像大小,使其在它適合的容器

#profile_pic{ 
    position:absolute; 
    border:1px solid #E1E3E4; 
    left:25px; 
    top: 25px; 
    width: 200px; 
    height: 200px; 
} 

由於我的應用程序可以是任何圖像(任意大小的)資料圖片,股利或形象,應該靈活適應對方。我已經測試了尺寸爲300px width300px height的個人資料圖片,並且圖像在div中完美呈現。然而,當我上傳一張圖片說,550px width400px width圖像顯示「壓扁」,這是可以理解的。

有兩個選項,1.調整圖像的大小,使整個圖像出現在div中,2.裁剪圖像,使圖像適應div大小。我不介意採用這兩種方法,但我無法在代碼中實現這些方法。

我試圖設置:

#profile_pic {width: 50%} 
#profile_pic img {width:100%} 

但它是行不通的。如何讓div(或圖像)始終適合div的大小,而不會丟失圖像的質量?

+0

如果你只是把'最大寬度:100%;最大高度:100%;'沒有寬度或高度爲 – SmokeyPHP

+1

你能澄清HTML佈局 - 有一個div與'img'裏面還是你設置div的'background-image'屬性? – RamRaider

回答

1

你可以只添加background-size:contain;到具有圖像股利(假設你設置的背景圖像所需的圖像。

失去質量是另一回事,縮放說50x50px圖像爲100x100要輸質量,所以它很可能是最好設置一個最小尺寸的資料圖片即可。

0

你可以設置max-widthmax-height以調整圖像大小以適應箱內無溢出,加入行高和文字對齊如果它的盒子比例不一致,則顯示中心圖像

#profile_pic, 
 
.profile_pic2 { 
 
    position: absolute; 
 
    border: 1px solid #E1E3E4; 
 
    left: 25px; 
 
    top: 25px; 
 
    width: 200px; 
 
    height: 200px; 
 
    line-height: 197px; 
 
    /* since image is the one and single child */ 
 
    text-align: center; 
 
    border: solid; 
 
    /*demo purpose */ 
 
} 
 
.profile_pic2 { 
 
    left: 250px; 
 
} 
 
.profile_pic2 +.profile_pic2 { 
 
    left: 450px; 
 
} 
 
#profile_pic img, .profile_pic2 img { 
 
    max-width: 100%; 
 
    max-height: 100%; 
 
    vertical-align: middle; 
 
    /* set on middle baseline setted at 200px */ 
 
}
<div id="profile_pic"> 
 
    <img src="//lorempixel.com/640/480"> 
 
</div> 
 
<div class="profile_pic2"> 
 
    <img src="//lorempixel.com/480/640"> 
 
</div> 
 
<div class="profile_pic2"> 
 
    <img src="//lorempixel.com/480/480"> 
 
</div>

相關問題