Home > Enterprise >  why the red part doesn't take only 100% of the available height
why the red part doesn't take only 100% of the available height

Time:07-25

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 ></div>
      <div ></div>
      <div ></div>
  </body>

CodePudding user response:

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;
}

CodePudding user response:

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 ></div>
    <div ></div>
    <div ></div>
  </div>
</section>
<section>
  <header>CSS Grid</header>
  <div id="grid">
    <div ></div>
    <div ></div>
    <div ></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 ></div>
  <div ></div>
  <div ></div>
</div>

  • Related