简体   繁体   中英

How can I calculate element dimensions based on sibling element dimensions?

I am trying to find a way to calculate an element's height based on the height of its sibling elements. In the code snippet below, children one and three have a height of 20%, and a max-height of 70px. I need to find a way to get child two to fill the remainder of the height, regardless of the container size, which is variable height: calc(100vh - 12vmin - 40px); . I have tried media queries and the calc() function, but neither work because of the variable container height. I am thinking that I will need to use JS, but any solution without it is preferable.

Thanks for any help!

PS If you have a solution with JS, please use 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> 

CSS flexbox is the way to go.

Change height on container to height: 100vh , add display: flex and flex-direction: column .

For childTwo remove the setting of height altogether and add 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM