flexbox sticky footer

2019-05-29 10:40发布

问题:

I'm trying to achieve more or less the same of what is described in this question:

  • Align an element to bottom with flexbox

except for the fact that i can't use fixed heights.

I have set of two cards that are already in a flex context (their heights are stretched with flexbox):

Inside the card I have a series of elements:

  • a header
  • a body
  • a footer (the blue div)

What I want is the footer to always stick to the bottom.

The inner container of the three elements described above have the following CSS:

.card-inner {
  display:flex;
  flex-flow :row wrap;
  align-items: stretch;
}

and the items inside have

.card {
  &-header,
  &-body {
    flex: 0 1 100%;
  }
  &-footer {
    flex: 0 1 100%;
    align-self:flex-end;
    margin-top: auto;
  }
}

I would have expected that align-self:flex-end or margin-top: auto would have pushed the footer div down the card, but this is not happening.

Maybe the two flex contexts don't speak to each other and are not related? Or maybe without a height to the inner container, the flex context ends when the content flow ends?

Is there a way to achieve this using no heights with flexbox?

Here's a codepen example: https://codepen.io/vlrprbttst/pen/QgWbEr

回答1:

Add display: flex to .card.

That will allow the children to use the full height of .container.

It will also pin the footer to the bottom.

revised demo


For a more comprehensive fix (if necessary), you will need to switch the flex-direction of .container-inner to column, and make adjustments to the flex items to account for this switch.

revised demo


The reason why align-self: flex-end and margin-top: auto didn't work has to do with the flex lines in a multi-line flex container.

Essentially, because of the way align-content works, your footer cannot break out of its flex line and shift to the bottom of the container.

For a complete explanation, see this post:

  • How does flex-wrap work with align-self, align-items and align-content?