Search code examples
htmlcsslayoutflexbox

How do I get a flexbox to have a center fixed and a bottom fixed children together?


I am trying to get a layout of the following kind via flexbox.

|                      |
|                      |
| CENTER FIXED ELEMENT |
|                      |
| BOTTOM FIXED ELEMENT |

This is my rough flexbox CSS.

.wrapper{
    display:flex;
    justify-content:center;
    flex-direction:column;
}
.bottom-element {
    align-self:flex-end;
}

The idea behind is that anything inside wrapper would get center aligned and .bottom-element would align itself to the bottom of the box.

This however doesn't work as expected and bottom element appears right after the center element.

Any other way this could be solved? or a silly something I might have missed?


Solution

  • Update 1:

    Center 'middle' div vertically of the whole 'wrapper'.

    .wrapper {
      height: 100px;
      width: 100px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
      border: 1px solid red;
    }
    
    .middle,
    .bottom {
      background: aqua;
    }
    
    .bottom {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
    }
    <div class="wrapper">
      <div class="middle">middle</div>
      <div class="bottom">bottom</div>
    </div>

    Update 2:

    Center 'middle' div vertically within the available space of 'wrapper' minus 'bottom'.

    .wrapper {
      height: 100px;
      width: 100px;
      display: flex;
      flex-direction: column;
      border: 1px solid red;
    }
    
    .middle,
    .bottom {
      background: aqua;
      margin-top: auto;
    }
    <div class="wrapper">
      <div class="middle">middle</div>
      <div class="bottom">bottom</div>
    </div>

    Previous answer:

    The idea is creating an empty placeholder for the top element with CSS pseudo content, and then just use flex-direction: column; + justify-content: space-between; to align all the 3 elements vertically.

    Note: the middle div might not be absolutely in the middle when comes to multiple lines of text in the flex items.

    .wrapper {
      height: 100px;
      width: 100px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      border: 1px solid red;
    }
    
    .wrapper:before {
      content: "\00A0";
    }
    
    .wrapper>div {
      background: aqua;
    }
    <div class="wrapper">
      <div>middle</div>
      <div>bottom</div>
    </div>