Home > Back-end >  CSS: Have content take up remaining height and its children share the same height equally
CSS: Have content take up remaining height and its children share the same height equally

Time:06-23

Here is a link to a CodeSandbox with the code below.

There is a div with a class of content that I want to take up the remaining height and have the children share the rest of the height (2 children => both take half; 3 children => each takes a third etc.), while taking up the full width.

I can't for the life of me figure out how to do this. I tried both grid and flex approaches, but wasn't able to make either work.

How would you achieve this layout?

The code:

index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app" >
      <h1 >My Title</h1>
      <nav >
        <li>some</li>
        <li>nav</li>
        <li>items</li>
      </nav>

      <header>
        <h2>
          Where do you want to go?
        </h2>
      </header>

      <!-- Content should take all of the remaining available height -->
      <div >
        <!-- Link 1, 2, and 3 should take a third of content's height each and take up the full width -->
        <a>Link 1</a>
        <a>Link 2</a>
        <a>Link 3</a>
      </div>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

index.js:

import "./styles.css";

styles.css:

body {
  font-family: sans-serif;
}

html,
body {
  height: 100%;
}

.app {
  min-height: 100%;
}

.nav {
  display: flex;
}

.content {
  display: flex;
  flex-direction: column;
}

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border-width: 0;
}

CodePudding user response:

Using flex:

body {
  font-family: sans-serif;
}

html,
body {
  height: 100%;
  min-height: 100%;
  margin: 0;
  padding: 0;
}

.app {
  min-height: 100%;
  background: #00fa
}

.app,
.content {
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  background: #fe0;
}

.content > a {
  flex: 1;
  border:solid 1px;
}

.nav {
  display: flex;
}
<div id="app" >
  <nav >
    <li>some</li>
    <li>nav</li>
    <li>items</li>
  </nav>

  <header>
    <h2>
      Where do you want to go?
    </h2>
  </header>

  <!-- Content should take all of the remaining available height -->
  <div >
    <!-- Link 1, 2, and 3 should take a third of content's height each and take up the full width -->
    <a>Link 1</a>
    <a>Link 2</a>
    <a>Link 3</a>
  </div>
</div>

  • Related