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)
.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. You can use calc()
function of css for it.
.red {
height: calc(100% - 10px - 40px);
background-color: red;
}
Percentages in CSS are relative to another value . In this case, your percentage is relative to the parent's height
property.
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
.
To redistribute remaining space automatically, you can use Flexbox or 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 { --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>
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.