使用 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 实现,但我无法让它工作。

原文由 supersize 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 394
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 */

 .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>

或者,您可以使 a 之前的元素增长以填充可用空间:

 p { flex-grow: 1; } /* Grow to fill available space */

 .content {
  height: 200px;
  border: 1px solid;
  display: flex;
  flex-direction: column;
}
h1, h2 {
  margin: 0;
}
p {
  flex-grow: 1;
}
 <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>

原文由 Oriol 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

 .container {
  display: flex;
}

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

最好的办法是将 position: absolute 设置为按钮并将其设置为 bottom: 0 ,或者您可以将按钮放在容器外并使用 negative transform: translateY(-100%) 将其放入容器中这个:

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

检查这个 JSFiddle

原文由 Roumelis George 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题