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

16

我有三个并排的div,使用display:flex进行布局。

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

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

这样链接将始终排列整齐。

JSFiddle 代码

2个回答

14

以下是两种方法:

嵌套 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 */

演示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 */
}

第三种方法涉及将flex-direction切换为column。但在某些情况下,更改弹性方向不是可接受的选项,因为它会改变布局的行为。 (由于这种方法已经发布在另一个答案中,因此本文不详细介绍。)


DEMO 2


12

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

示例更新

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

谢谢伙计!margin-top对我很有帮助。 - hayatbiralem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接