2016-04-15 64 views
5

我有一個100 * 300px div(演示值,實際值不同而且未知)內的240 * 240px圖像。我使用object-fit: contain使圖像在div內完全可見,並保持其寬高比。問題是object-fit沒有修改圖像的寬度,導致了一個奇怪的「填充」(可以這麼說)。爲什麼對象不適合影響寬度或高度?

enter image description here

我如何可以使圖像取,而不是採取原來的寬度只需要儘可能多的寬度?

演示:http://codepen.io/alexandernst/pen/ONvqzN

.wrapper { 
 
    height: 100px; 
 
    width: 300px; 
 
    border: 1px solid black; 
 
} 
 
.flex { 
 
    display: flex; 
 
} 
 
img { 
 
    object-fit: contain; 
 
}
<div class="flex wrapper"> 
 
    <img src="https://unsplash.it/240/240" /> 
 
</div>

+0

你是什麼意思「不修改寬度?」它將圖像縮小到100px高度,同時保持寬高比不變。填充每邊正好是70px,因爲在調整到100x100之後,剩下140px(70px * 2)。 – theblindprophet

+0

@theblindprophet我的意思是'img'的總寬度大於可見圖像。我想要做的就是讓'img'元素佔用與實際圖像(在這種情況下爲100px寬度)相同的寬度,而不是原始圖像的寬度(240px)。 – alexandernst

+0

啊,所以它會滑到左邊,(例如)你可以在'div'的其餘部分爲其他元素留出空間嗎? – theblindprophet

回答

-1

.wrapper { 
 
    height: auto; 
 
    width: 100%; 
 
    border: 1px solid black; 
 
    background-image: url(https://unsplash.it/240/240); 
 
    background-size: contain; 
 
    background-repeat: no-repeat; 
 
    background-position: center; 
 
} 
 

 
.flex { 
 
    display: flex; 
 
} 
 

 
img { 
 
    object-fit: contain; 
 
}
<div class="flex wrapper"> 
 
    <img src="https://unsplash.it/240/240" /> 
 
</div>

+0

這是一個很大的'不'我不知道從哪裏開始:/ – alexandernst

+0

你的意思是你不明白我給你的代碼,或者是它不工作? – mlegg

+0

它不工作,你刪除了固定高度,這表明問題。 – alexandernst

1

object-fit屬性通常與width一起工作,heightmax-width一nd max-height。例如:

.wrapper { 
 
    height: 100px; 
 
    width: 300px; 
 
    border: 1px solid black; 
 
} 
 
.flex { 
 
    display: flex; 
 
} 
 
img { 
 
    object-fit: contain; 
 
    height: 100%; 
 
    width: auto; 
 
}
<div class="flex wrapper"> 
 
    <img src="https://unsplash.it/240/240" /> 
 
</div>

事實上,它工作正常過,即使沒有object-fit,看到這個jsFiddle

相關問題