2017-08-01 45 views
1

如果我創建使用Flex盒包裝的div的2x2的網格,然後將圖像中的每個格: -一個柔性包裝元素中設置圖像的高度

<div id="wrapper"> 
    <div class="item"><img src="http://via.placeholder.com/100x500"></div> 
    <div class="item"><img src="http://via.placeholder.com/100x500"></div> 
    <div class="item"><img src="http://via.placeholder.com/100x500"></div> 
    <div class="item"><img src="http://via.placeholder.com/100x500"></div> 
</div> 

#wrapper { 
    display: flex; 
    flex-wrap: wrap; 
    height: 100vh; 
    background-color: burlywood; 
} 
.item { 
    flex-grow: 1; 
    width: 50%; 
    background-colour: bisque; 
} 

如果圖像的原始高度比Flex項目更深,它會將我的內容推向比我設置包裝的100vh更深的地方。

我希望每個圖像都填充其flex元素div的高度,在本例中爲屏幕高度的50%,圖像寬度爲正確的比例。

我試過將圖像高度設置爲其容器的100%,但我無法使其工作。 (除非圖像原生高度較短,則會展開以適合)。

它也適用,如果我明確地設置Flex項目divs的高度爲33.333%,但這似乎不是對我來說正確的解決方案。

+0

我希望避免一個解決方案,其中涉及設置.item divs的高度,雖然它在這個簡單的例子中起作用,但它導致我進一步的問題與我的佈局 – marcovanbostin

+0

有關最大高度而不是高度在他們?會不會影響佈局? – Frits

+0

我正在設置一些具有固定px大小的元素,並通過設置一個元素爲flex-grow來填充剩餘的空白空間,如果必須給該元素一個大小,或者我認爲它的最大大小不起作用,我想我需要回到製圖板。 – marcovanbostin

回答

0

您只需設置圖像的高度,使其保持正確的比例。將以下類添加到您的CSS,以應用50vh的高度,如果我正確理解了您的問題,我認爲您的問題將得到解決。

.item img { 
    height:50vh; 
} 

你可以隨時調整以獲得你需要的東西。

希望這會有所幫助。

+1

感謝@trevorp正確地格式化我的答案。 –

1

另一種解決方案是將.item高度設置爲50%,而給予.item img最大高度,就像這樣:

#wrapper { 
 
    display: flex; 
 
    flex-wrap: wrap; 
 
    height: 100vh; 
 
    background-color: burlywood; 
 
} 
 
.item { 
 
    flex-grow: 1; 
 
    width: 50%; 
 
    background-color: bisque; 
 
    height: 50%; 
 
} 
 
.item > img { 
 
    max-height: 100%; 
 
}
<div id="wrapper"> 
 
    <div class="item"><img src="http://via.placeholder.com/100x500"></div> 
 
    <div class="item"><img src="http://via.placeholder.com/100x500"></div> 
 
    <div class="item"><img src="http://via.placeholder.com/100x500"></div> 
 
    <div class="item"><img src="http://via.placeholder.com/100x500"></div> 
 
</div>

這裏的a fiddle如果這是你的偏好。

+0

這裏是[另一個小提琴](https://jsfiddle.net/3yaexkdr/2/),它將顯示輪廓 - 僅僅是因爲它更容易看到它的工作方式...... :) – Frits

相關問題