Search code examples
htmlcsspositionabsolute

Position absolute but relatif


Currently I use this CSS to place a div (.child_bottom) at the bottom of its parent and another div above it (.child) because I know the height of (.child_bottom).

The parent at a variable height.

.parent
{
  position:relative;
}

.child
{
  position:absolute;
  bottom:250px;
}

.child_bottom
{
  position:absolute;
  bottom:0;
  height:250px;
}
<div class="parent">

  <div class="child"></div>
  
  <div class="child_bottom"></div>

</div>

But I would like to obtain the same thing with a variable height of .child_bottom, how to do?

Thank you in advance for your help.


Solution

  • Using flex would allow you to remove all of the absolute positioning:

    .parent {
      height: 400px;
      outline: 1px solid blue;
      
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
    }
    
    .child {
      background: green;
    }
    
    .child_bottom {
      background: orange;
      height: 250px;
    }
    <div class="parent">
    
      <div class="child">CHILD</div>
    
      <div class="child_bottom">CHILD_BOTTOM</div>
    
    </div>

    If you did wish to add content before .child, remove the justify-content and make this content flex: 1:

    .parent {
      display: flex;
      flex-direction: column;
      /* justify-content: flex-end; */
      height: 400px;
      outline: 1px solid blue;
    }
    
    .child {
      background: green;
    }
    
    .child_bottom {
      background: orange;
      height: 250px;
    }
    
    .other_content {
      background: yellow;
      flex: 1;
    }
    <div class="parent">
    
      <div class="other_content">
        OTHER_CONTENT (Fills the space)
      </div>
    
      <div class="child">CHILD</div>
    
      <div class="child_bottom">CHILD_BOTTOM</div>
    
    </div>