How to Fix Element to Bottom of Container with CSS

How to fix an element to the bottom of a container with CSS? If it is the bottom of the page, we can directly position: fixed; bottom: 0; directly based on browser positioning. But the effect he wants is based on the parent container, so we must use other means to locate it.

For example, we can use relative to limit absolute, then bottom: 0. However, it will cause abnormal display when the content is too long. So, we need to do inner scrolling. If doing internal rolling, then we need to be able to prop open the box. Absolute positioning is no longer required.

Let's look at three implementations of fixing elements to the bottom of the container.

CSS: Use flex to Fix Element to Bottom of Container

The parent uses a flex layout, and the columns are arranged vertically. The parent's height (height, maxHeight) is set, and the .content child flex: auto; is automatically stretched. Or use .content as a height limit. Footer can use absolute plus padding. Or relying entirely on the document flow layout is fine.

  .demo1{
      position: relative;
      padding-bottom: 40px;
      display: inline-flex;
      flex-direction: column;
  }
  .demo1 .footer{
      position: absolute;
      bottom: 0;
      left: 0;right: 0;
      margin: 0;
  }
  .demo1 .content{
      overflow: auto;
  }

CSS: Use calc to Fix Element to Bottom of Container

If the flex is not used, then we can use calc to subtract the header and footer space.

<style>
    .demo3{
        position: relative;
    }
    .demo3 .content{
        overflow: auto;
        max-height: calc(100% - 40px);
    }
</style>

CSS: Use absolute to Fix Element to Bottom of Container

If calc doesn't work well, you can also use absolute to get all elements out of the flow of the document.

<style>
    .demo4{
        position: relative;
    }
    .demo4 .header,.demo4 .footer{
        position: absolute;
        margin: 0;
        top:0;left:0 ;right:0;
    }
    .demo4 .footer{
        top: auto;
        bottom: 0;
    }
    .demo4 .content{
        overflow: auto;
        height: 100%;
        padding-top: 30px;
        padding-bottom: 30px;
        margin: 0;
        box-sizing: border-box;
    }
</style>


Leave a reply



Submit