简体   繁体   中英

total summed height of children elements are bigger than parent's height

In this experiment, the first child is only formed by padding, while the second child has to fill the remaining space of the parent container. To solve this, I tried using the calc() function, I subtracted 100vh , which is the height of the parent element, by the total sum of padding-top and padding-bottom of the first element, which is 6rem . The result I got was a height exceeding the height of the remaining space of the parent element, leaving an overflow. 在此处输入图片说明

 .container { width: 100%; height: 100vh; background: #dfdfdf; } .first-box { width: 100%; padding: 3rem 0; background: firebrick; color: #dfdfdf; font: 1rem 'Arial', Helvetica, sans-serif; display: flex; align-items: center; justify-content: center; } .second-box { width: 100%; height: calc(100vh - 6rem); background: purple; color: #dfdfdf; font: 1rem 'Arial', Helvetica, sans-serif; display: flex; align-items: center; justify-content: center; } 
 <div class="container"> <div class="first-box">This box has no height, only formed by padding</div> <div class="second-box">This box must fill the whole container with the remaining offset height of parent</div> </div> 

Should I use Javascript instead in a case like this? Because unlike in CSS, you can get the offset height of an element in Javascript whether it's formed by height or padding only.

You're already using flexbox so apply that to your container and let it deal with the height.

Your container will also need flex-direction to be set to column. Then remove the height property from your second box and add flex: 1 1 auto; .

Keep in mind that I haven't added any vendor prefixes in my example.

 .container { display: flex; flex-direction: column; width: 100%; height: 100vh; background: #dfdfdf; } .first-box { width: 100%; padding: 3rem 0; background: firebrick; color: #dfdfdf; font: 1rem 'Arial', Helvetica, sans-serif; display: flex; align-items: center; justify-content: center; } .second-box { width: 100%; background: purple; color: #dfdfdf; font: 1rem 'Arial', Helvetica, sans-serif; display: flex; align-items: center; justify-content: center; flex: 1 1 auto; } 
 <div class="container"> <div class="first-box">This box has no height, only formed by padding</div> <div class="second-box">This box must fill the whole container with the remaining offset height of parent</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