skip to Main Content

I have written the HTML code like this:

<div id="FirstDiv"></div>
<div id="SecondDiv"></div>
<div id="TARGETDIV"></div>

And CSS code like this:

#FirstDiv {
  width: 100vw;
  height: 50px;
}

#SecondDiv {
  width: 100vw;
  height: 230px;
}

#TARGETDIV {
  width: 100vw;
  height: /* What code should be here? */;
}

I have already set the height of FirstDiv and SecondDiv, and I want to make the TARGETDIV height as large as possible to fit the user’s screen size.
How can I write CSS code like that?

2

Answers


  1. You can use the vh unit and calc in your height setting:

    height: calc(100vh - 230px - 50px);
    

    Meaning: Full viewport height minus heights of the other two divs:

    (Note: View the snippet in full page view to see the correct result – the first two divs together are already higher than the snippet window)

    html, body {
    margin: 0;
    }
    #FirstDiv {
      width: 100vw;
      height: 50px;
      background: blue;
      
    }
    
    #SecondDiv {
      width: 100vw;
      height: 230px;
      background: red;
    }
    
    #TARGETDIV {
      width: 100vw;
      height: calc(100vh - 230px - 50px);
      background: green;
    }
    <div id="FirstDiv"></div>
    <div id="SecondDiv"></div>
    <div id="TARGETDIV"></div>
    Login or Signup to reply.
  2. The modern way would probably be to use a flexbox and put a flex-grow on the target div. Using the CSS calc function like others said also works, but isn’t dynamic

    (On StackOverflow you have to click on the "Full Page" link after pressing "Run" to be able to see it)

    body {
      margin: 0; /* removes spacing outside page */
      display: flex;
      flex-direction: column;
      height: 100vh; /* make body screen height */
    }
    
    #FirstDiv {
      background: green;
      width: 100vw;
      height: 50px;
    }
    
    #SecondDiv {
      background: red;
      width: 100vw;
      height: 230px;
    }
    
    #TARGETDIV {
      flex-grow: 1; /* Set flex grow so the div takes up remaining space */
      background: blue;
      width: 100vw;
    }
    <body>
      <div id="FirstDiv"></div>
      <div id="SecondDiv"></div>
      <div id="TARGETDIV"></div>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search