我有一个`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可以做到这一点,但我无法做到。
你可以使用自动页边距。
在通过
justify-content
和align-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>
.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>
<!--结束片段-->。
你可以使用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][1] 。
使用 "align-self: flex-end; "的解决方案对我来说并不奏效,但如果你想使用flex,这个解决方案就奏效了。
-------------------
|heading 1 |
|heading 2 |
|paragraph text |
| |
| |
| |
|link button |
-------------------
_*注意:当"运行该代码片段"时,你必须向下滚动才能看到底部的链接。
<! -- begin snippet: js hide: false console: true babel: false -->
.content {
display: flex;
justify-content: space-between;
flex-direction: column;
height: 300px;
}
.content .upper {
justify-content: normal;
}
/* Just to show container boundaries */
.content .upper, .content .bottom, .content .upper > * {
border: 1px solid #ccc;
}
<div class="content">
<div class="upper">
<h1>heading 1</h1>
<h2>heading 2</h2>
<p>paragraph text</p>
</div>
<div class="bottom">
<a href="/" class="button">link button</a>
</div>
</div>