1

I have a parent div and two child divs. The second child div is variable height, but is absolutely positioned at the bottom of the parent div.

I want the first div to have a dynamic height based on the second div. I thought margin-bottom: 10px would specify the height of the first div to go up until 10px of the second div, but apparently this is not true.

Is there any workaround to get what I want?

HTML:

<div class="parent">
  <div class="first">
     Hello
  </div>
  <div class="second" >
  </div>
</div>

CSS:

.parent {
  height: 500px;
  min-width: 500px;
  position: relative;
  background-color: red;
}

.first {
  background-color: green;
  margin-bottom: 10px;
}

.second {
  height: 100px;
  background-color: grey;
  bottom: 0px;
  box-sizing: border-box;
  position: absolute;
  width: 100%;
}

JSFiddle: https://jsfiddle.net/4tjqsron/2/

user3642365
  • 549
  • 1
  • 6
  • 16

2 Answers2

0

The margin-bottom is only telling the browser "don't let anything come within 10px of the bottom of me," as you found out.

I think this may be an excellent opportunity to use the calc() css function!

Try this:

.first {
     background-color: green;
     height: calc(100% - 110px);
}

This should leave a 10px space between your first and second child element. Basically it is telling the browser that the first element is to take up 100% of its parent minus 110px. Please see this for more info on the calc() function. https://www.w3schools.com/cssref/func_calc.asp I hope this helps!

EDIT: It just occurred to me that this only works if your height is set elsewhere. You may need to adjust your use of the 100% argument depending on your current parent height settings. Even if this is the case, the calc() function should still prove useful.

Dominic Fox
  • 118
  • 11
0

I am not get your point very clearly, here is my solution that div.second will always align on the bottom of div.parent vertically:

.parent {
  height: 500px;
  min-width: 500px;
  position: relative;
  background-color: red;
}

.first {
  background-color: green;
  margin-bottom: 10px;
}

.second {
/*   height: 100px;
  background-color: grey;
  bottom: 0px;
  box-sizing: border-box;
  position: absolute;
  width: 100%; */
  max-height: 100%;
  position: absolute;
  top: auto;
  bottom: 0;
}
<div class="parent">
  <div class="first">
     Hello
  </div>
  <div class="second" >No matter how many content in this div, it will always lie on the bottom of the parent div</div>
</div>
1Cr18Ni9
  • 1,737
  • 1
  • 12
  • 21