Home > Mobile >  Flex layout grow top div to take remaining space
Flex layout grow top div to take remaining space

Time:03-13

I have a scenario when I want the top div to take ramaining space when bottom is re-positioned with "bottom" css.

enter image description here

div#container {
  display: flex;
  flex-direction: column;
  border: 2px solid green;
  width: 100%;
  height: 200px;
}

div#body {
  position: static;
  border: 2px solid red;
  flex: 1;
}

div#footer {
  position: relative;
  border: 2px solid blue;
  height: 50px;
  bottom: -15px;
}
<div id="container">
  <div id="body">Body content</div>
  <div id="footer">footer</div>
</div>

I have a codepen to illustrate the problem: https://codepen.io/ydubey/pen/MWrWpNp

I want the body (marked by red border) to grow and take the space left by the footed (marked by blue border).

Thanks in advance :)

CodePudding user response:

Use margin instead of a standard bottom value. With #body set at 100%, the browser won't be able to distinguish the flex-grow, if you use the bottom value on #footer.

html,
body {
  height: 100%;
}

div#container {
  display: flex;
  flex-direction: column;
  border: 2px solid green;
  width: 100%;
  height: 200px;
}

div#body {
  position: static;
  border: 2px solid red;
  flex: 1;
  height: 100%;
}

div#footer {
  border: 2px solid blue;
  height: 50px;
  position: relative;
  margin-bottom: -15px;
}
<div id="container">
  <div id="body">Body content</div>
  <div id="footer">footer</div>
</div>

CodePudding user response:

You can achieve what you're looking for using CSS calc().

Here's how I refactored your code, hope it helps!

div#container {
  display: flex;
  flex-direction: column;
  border: 2px solid green;
  height: 200px;
}

div#body {
  position: static;
  border: 2px solid red;
  height: calc(100% - 50px); /* Subtracting the footer height to the body */
}

div#footer {
  position: relative;
  border: 2px solid blue;
  height: 50px;
}
<div id="container">
    <div id="body">Body content</div>
    <div id="footer">footer</div>
</div>

CodePudding user response:

I am not sure if I understood you correctly, but try it with that.

div#container {
  display: flex;
  flex-direction: column;
  border: 2px solid green;
  width: 100%;
  height: 200px;
}

div#body {
  position: static;
  border: 2px solid red;
  height: 100%;
}

div#footer {
  position: relative;
  border: 2px solid blue;
  height: 50px;
  bottom: 0;
}
  • Related