使用 flexbox 将元素与底部对齐 [英] Align an element to bottom with flexbox

查看:34
本文介绍了使用 flexbox 将元素与底部对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div 和一些孩子:

<h1>标题1</h1><h2>标题2</h2><p>一些或多或少的文字</p><a href="/" class="button">点击我</a>

我想要以下布局:

 -------------------|标题 1 ||标题 2 ||段落文本 ||可以有很多||行 ||||||||链接按钮|-------------------

无论 p 中有多少文本,我都想将 .button 始终放在底部而不将其从流程中取出.我听说这可以通过 Flexbox 实现,但我无法让它工作.

解决方案

您可以使用 auto边距

<块引用>

在通过 justify-content 对齐之前a> 和 align-self,任何正的可用空间都分配到自动边距中维度.

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

p { margin-bottom: auto;}/* 将以下元素推到底部 */一个 { 边距顶部:自动;}/* 将它和后面的元素推到底部 */

.content {高度:200px;边框:1px 实心;显示:弹性;弹性方向:列;}h1, h2 {边距:0;}一种 {边距顶部:自动;}

<h1>标题1</h1><h2>标题2</h2><p>一些文字或多或少</p><a href="/" class="button">点击我</a>

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

p { flex-grow: 1;}/* 增长以填充可用空间 */

.content {高度:200px;边框:1px 实心;显示:弹性;弹性方向:列;}h1, h2 {边距:0;}p{弹性增长:1;}

<h1>标题1</h1><h2>标题2</h2><p>一些文字或多或少</p><a href="/" class="button">点击我</a>

I have a div with some children:

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

and I want the following layout:

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

Regardless how much text is in the p I want to stick the .button always at the bottom without taking it out of the flow. I've heard this can be achievable with Flexbox but I can't get it to work.

解决方案

You can use auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

So you can use one of these (or both):

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>

Alternatively, you can make the element before the a grow to fill the available space:

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>

这篇关于使用 flexbox 将元素与底部对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆