2017-10-06 228 views
0

我想找到一種方法來根據它的兄弟元素的高度來計算元素的高度。在下面的代碼片段中,第一個和第三個孩子的高度爲20%,最大高度爲70px。我需要找到一種方法讓孩子二來填充身高的其餘部分,而不管容器大小如何,這是可變的height: calc(100vh - 12vmin - 40px);。我已經嘗試了媒體查詢和calc()函數,但因爲可變容器高度而不工作。我想我會需要使用JS,但沒有它的任何解決方案都是可取的。如何根據同胞元素尺寸計算元素尺寸?

感謝您的幫助!

P.S.如果你有JS的解決方案,請使用vanilla JS。

#container { 
 
    border: 4px solid #000000; 
 
    box-sizing: border-box; 
 
    height: calc(100vh - 12vmin - 40px); 
 
    max-width: 600px; 
 
    width: 100%; 
 
} 
 

 
#childOne { 
 
    border: 2px solid blue; 
 
    box-sizing: border-box; 
 
    height: 20%; 
 
    max-height: 70px; 
 
} 
 

 
#childTwo { 
 
    border: 2px solid red; 
 
    box-sizing: border-box; 
 
    height: 60%; 
 
} 
 

 
#childThree { 
 
    border: 2px solid yellow; 
 
    box-sizing: border-box; 
 
    height: 20%; 
 
    max-height: 70px; 
 
}
<div id="container"> 
 
    <div id="childOne"></div> 
 
    <div id="childTwo"></div> 
 
    <div id="childThree"></div> 
 
</div>

回答

2

CSS Flexbox的是要走的路。

更改容器高度爲height: 100vh,加display: flexflex-direction: column

對於childTwo完全刪除高度的設置,並添加flex:1

body { 
 
     margin: 0; 
 
     padding: 0; 
 
    } 
 
    
 
    #container { 
 
     border: 4px solid #000000; 
 
     box-sizing: border-box; 
 
     display: flex; 
 
     flex-direction: column; 
 
     height: 100vh; 
 
     max-width: 600px; 
 
     width: 100%; 
 
    } 
 

 
    #childOne { 
 
     border: 2px solid blue; 
 
     box-sizing: border-box; 
 
     height: 20%; 
 
     max-height: 70px; 
 
    } 
 

 
    #childTwo { 
 
     border: 2px solid red; 
 
     box-sizing: border-box; 
 
     flex: 1; 
 
    } 
 

 
    #childThree { 
 
     border: 2px solid yellow; 
 
     box-sizing: border-box; 
 
     height: 20%; 
 
     max-height: 70px; 
 
    }
<div id="container"> 
 
     <div id="childOne"></div> 
 
     <div id="childTwo"></div> 
 
     <div id="childThree"></div> 
 
    <div>

+0

可以放回可變高度,這應該仍然工作。只要你在容器上設置了一定的高度(不是百分比,除非父母有一個高度),那麼中間的div將填充剩餘的空間。 – wlh