[英]why the red part doesn't take only 100% of the available height
why the red part doesn't take only 100% of the height available i mean why the red part take 100% of 100vh and not 100vh - 10px - 40px (black and blue heights)为什么红色部分不只占可用高度的 100% 我的意思是为什么红色部分占 100vh 的 100% 而不是 100vh - 10px - 40px(黑色和蓝色高度)
.black { height: 10px; background-color: black; }.red { height: 100%; background-color: red; }.blue { height: 40px; background-color: blue; } body { height: 100vh; margin: 0; padding: 0; }
<body> <div class="black"></div> <div class="red"></div> <div class="blue"></div> </body>
100% is not calculating remaining available part for you. 100% 不会为您计算剩余的可用部分。 You can use
calc()
function of css for it.您可以使用 ZC7A628CBA22E28EB17B5F5C6AE2A266AZ 的
calc()
function 。
.red {
height: calc(100% - 10px - 40px);
background-color: red;
}
Percentages in CSS are relative to another value . CSS 中的百分比是相对于另一个值的。 In this case, your percentage is relative to the parent's
height
property.在这种情况下,您的百分比是相对于父级的
height
属性的。
Since the red element is 100% of the parent's height
, and the parent's height is 100vh
, the red element will also have a height of 100vh
.由于红色元素是父元素高度的 100%,而父元素的
height
是100vh
,所以红色元素的高度也将是100vh
。
To redistribute remaining space automatically, you can use Flexbox or CSS Grid :要自动重新分配剩余空间,您可以使用Flexbox或CSS Grid :
/* Flexbox */ #flexbox { display: flex; flex-direction: column; } #flexbox.red {flex-grow: 1} /* CSS Grid */ #grid { display: grid; grid-template-rows: auto 1fr auto; } /* Presentational styling */ #flexbox, #grid { border: 1px solid black; height: 200px; }.black { height: 10px; background-color: black; }.red {background-color: red}.blue { height: 40px; background-color: blue; }
<section> <header>Flexbox</header> <div id="flexbox"> <div class="black"></div> <div class="red"></div> <div class="blue"></div> </div> </section> <section> <header>CSS Grid</header> <div id="grid"> <div class="black"></div> <div class="red"></div> <div class="blue"></div> </div> </section>
Alternatively, you can calculate the remaining space yourself with calc()
, either with magic numbers or by using custom properties :或者,您可以使用
calc()
自己计算剩余空间,使用幻数或使用自定义属性:
/* calc() */ #calc { --h-black: 10px; --h-blue: 40px; } #calc.red { height: calc(100% - var(--h-black) - var(--h-blue)); } /* Presentational styling */ #calc { border: 1px solid black; height: 200px; }.black { height: var(--h-black); background-color: black; }.red {background-color: red}.blue { height: var(--h-blue); background-color: blue; }
<div id="calc"> <div class="black"></div> <div class="red"></div> <div class="blue"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.