将元素与每个 flexbox 的底部居中对齐

Align an element to centre bottom of each flexbox

我有 3 个并排使用 display: flex 的 div。

这些 div 中的内容高度不同,但我想要在每个 div 中创建一个始终位于底部的 link。

 -----------   -----------   -----------
|    img    | |    img    | |    img    |
| heading 1 | | heading 3 | | heading 3 |
| paragraph | | paragraph | | paragraph |
| paragraph | |           | | paragraph |
|           | |           | | paragraph |
|   link    | |   link    | |   link    |
 -----------   -----------   ----------- 

这样 link 将始终排成一行。

JSFiddle code

您可以将.contentdisplay改为flex,然后添加flex-direction: column,使内容从上到下流动。为了将子锚元素定位在底部,只需添加 add margin-top: auto 即可:

Updated Example

.content {
  display: flex;
  flex-direction: column;
}
.content a {
  margin-top: auto;
}

这里有两种方法:

嵌套 Flexbox

.col {
    flex: 1;
    display: flex;                 /* create nested flex container */
    flex-wrap: wrap;               /* enable flex items to wrap */ 
    justify-content: center;       /* center flex items on each line */
}

.col > a { align-self: flex-end; } /* position link always at bottom */

DEMO 1


绝对定位

.col {
    flex: 1;
    position: relative;      /* establish containing block (nearest positioned ancestor)
                                for absolute positioning */
}

.col > a {
    position: absolute;
    bottom: 5px;                 /* adjust this value to move link up or down */
    left: 50%;                   /* center link horizontally */
    transform: translateX(-50%); /* center link horizontally */
}

DEMO 2


第三种方法涉及将 flex-direction 切换为 column。然而,在某些情况下,更改 flex 方向不是一个可接受的选项,因为它会更改布局的行为。 (此方法已在另一个答案中发布,此处不再详述。)