私は、いくつかの子供を持つ 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で実現できると聞いたことがありますが、なかなかうまくいきません。
オートマージン][1]を使用することができます。
また、justify-content`やalign-self`によるアライメントに先立って、[auto margins][1]を使用することができます。
正のフリースペースは、その次元のオートマージンに分配されます。 次元に分配されます。
ですから、これらのどちらか(または両方)を使うことができます。
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>
display: flexを使って要素を下に配置することもできますが、すべての要素に影響が出るので、この場合はflexを使いたくないと思います。
flexを使って要素を一番下に配置するには、次のようにします。
.container {
display: flex;
}
.button {
align-self: flex-end;
}
一番良い方法は、ボタンに position: absolute を設定して、bottom:あるいは、ボタンをコンテナの外に置いて、ネガティブな
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 |
-------------------
_Note: コードスニペットを実行する際には、下のリンクを見るためにスクロールダウンする必要があります。
.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>