Search code examples
htmlcsscss-positionpadding

How can I move elements to the bottom of parent considering the padding?


I want to position an element at the bottom of its parent div, but considering its parent bottom padding.

See the following example:

.container{
  height: 100px;
  padding-bottom: 100px;
  position: relative;
  background-color: grey;
}

.toBottom{
  margin: 0;
  position: absolute;
  bottom: 0;
}
<div class="container">
  <p class="toBottom">I am at the bottom</p>
</div>

In this example the text is right at the end of its parent, but I want it to be positioned at 100px from the bottom (because thats the padding of the parent).


Is this possible? I know I could just set the bottom value of the text to 100px, but I am interested if I can somehow do that.


Solution

  • Flexbox provides tools for this.

    .container {
      height: 100px;
      padding-bottom: 100px;
      background-color: grey;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
    }
    
    p {
      background: pink; /* demo only */
    }
    <div class="container">
      <p class="toBottom">I am at the bottom, but above padding</p>
    </div>

    If you have other content in the container, you can take a different approach.

    .container {
      height: 150px;
      padding-bottom: 100px;
      background-color: grey;
      display: flex;
      flex-direction: column;
      justify-content: start; /* actually the default (flex-start) */
    }
    
    .toBottom {
      margin-top: auto;
    }
    
    p {
      background: pink;
    }
    <div class="container">
      <p>Other content</p>
      <p class="toBottom">I am at the bottom, but above padding</p>
    </div>