0

There is the following HTML:

body {
  padding: 10px;
  border: 2px solid black;
  margin: 2px;
}
.div1 {
  height: 50px;
  border: 2px solid black;
}
.div2 {
  /* height: ??? */
  border: 2px solid black;
  margin-top: 2px;
  margin-bottom: 2px;
}
<body>
  <div id="div1" class="div1"></div>
  <div id="div2" class="div2"></div>
</body>

The height of div1 should be always static 50px, the rest of parent space should be filled with div2. For example,

if body.height == 700px then 
    div1.height = 50px
    div2.height = 650px

How to define and set this dynamic height for the div2?

Adam Shakhabov
  • 1,194
  • 2
  • 14
  • 35
  • flex or grid will help here : https://stackoverflow.com/questions/25098042/fill-remaining-vertical-space-with-css-using-displayflex/25098486#25098486 – G-Cyrillus Jun 12 '21 at 12:37

3 Answers3

-1

If the above is your exact case then you can use the css calc()

So, set your css like so:

#div1{
   height:50px;
}
#div2{
   height:calc(100% - 50px);
}

As long as there is a defined height on body, this should work

Ant
  • 1,083
  • 1
  • 15
  • 35
-1

grid, padding and box-sizing will help you here:

* {
  box-sizing: border-box;
  margin: 0;
}

html {
  padding: 2px;
  height: 100%;
}

body {
  padding: 10px;
  border: 2px solid black;
  /* added*/
  min-height: 100%;
  display: grid;
  grid-template-rows: 50px 1fr;
  gap: 2px;
}

.div1 {
  border: 2px solid black;
}

.div2 {
  border: 2px solid black;
  margin-top: 2px;
  margin-bottom: 2px;
}
<body>
  <div id="div1" class="div1"></div>
  <div id="div2" class="div2"></div>
</body>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
-1

You can use css flexbox

body {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0;
}
.div1 {
  height: 50px;
  border: 1px solid red;
}
.div2 {
  flex-grow: 1;
  border: 1px solid green;
}
cucaracho
  • 174
  • 6