2016-04-15 68 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

相关问题