提问者:小点点

用flexbox将元素底部对齐


我与一些孩子有div:

<div class="content">
  <h1>heading 1</h1>
  <h2>heading 2</h2>
  <p>Some more or less text</p>
  <a href="/" class="button">Click me</a>
</div>

我想要以下布局:

 -------------------
|heading 1          |
|heading 2          | 
|paragraph text     |
|can have many      |
|rows               |
|                   |
|                   |
|                   | 
|link-button        |
 -------------------

无论p中有多少文本,我都希望将.button始终贴在底部,而不将其从流中取出。我听说Flexbox可以实现这一点,但我不能让它工作。


共2个答案

匿名用户

可以使用自动边距

在通过justify-contentalign-self对齐之前,任何正的可用空间都会分配给该维度中的自动边距。

所以您可以使用其中之一(或两者):

p { margin-bottom: auto; } /* Push following elements to the bottom */
a { margin-top: auto; } /* Push it and following elements to the bottom */

null

.content {
  height: 200px;
  border: 1px solid;
  display: flex;
  flex-direction: column;
}
h1, h2 {
  margin: 0;
}
a {
  margin-top: auto;
}
<div class="content">
  <h1>heading 1</h1>
  <h2>heading 2</h2>
  <p>Some text more or less</p>
  <a href="/" class="button">Click me</a>
</div>

匿名用户

您可以使用Display:flex将一个元素定位到底部,但我认为您不希望在这种情况下使用flex,因为它会影响您的所有元素。

要使用flex将元素定位到底部,请尝试以下操作:

.container {
  display: flex;
}

.button {
  align-self: flex-end;
}

您最好的方法是将Position:absolute设置为按钮,并将其设置为bottom:0,或者您可以将按钮放置在容器外部,并使用负的Transform:translateY(-100%)将其放入容器中,如下所示:

.content {
    height: 400px;
    background: #000;
    color: #fff;
}
.button {
    transform: translateY(-100%);
    display: inline-block;
}

检查此JSFiddle