LoginSignup
1
1

More than 3 years have passed since last update.

flexboxで横並びにしたコンテンツの中の最後の要素(ボタン等)は下揃えにする方法

Posted at

どうも7noteです。横並びコンテンツの各要素の最後だけ下揃えにする方法について

先日ツイッターで見つけた画期的なアイデア・スタイルです。正直ちょっと感動しました。

Before
before.png

After
after.png

ガタガタになってしまうところをきれいに並べることができます!

ソース

index.html
<ul>
  <li>
    <figure class="thumb">
      <img src="sample.png" alt="画像">
    </figure>
    <p class="text">テキストが入ります。テキストが入ります。テキストが入ります。</p>
    <div class="btn">ボタン</div>
  </li>
  <li>
    <figure class="thumb">
      <img src="sample.png" alt="画像">
    </figure>
    <p class="text">テキストが入ります。</p>
    <div class="btn">ボタン</div>
  </li>
  <li>
    <figure class="thumb">
      <img src="sample.png" alt="画像">
    </figure>
    <p class="text">テキストが入ります。</p>
    <div class="btn">ボタン</div>
  </li>
</ul>
style.css
ul {
  margin: 0 0 30px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

ul li {
  width: 200px;           /* 各コンテンツの横幅 */
  border: 1px solid #000; /* 各コンテンツのborder */
  padding: 10px;          /* 余白の指定 */
  display: flex;          /* 【重要】フレックスボックスにする */
  flex-direction: column; /* 【重要】縦並びにする */
}

ul li .text {
  background: #ccc;       /* 背景色にグレーを指定 */
  margin: 0 0 10px;       /* 下に10pxの余白 */
  padding: 5px;           /* 余白5pxを指定 */
}

ul li .btn {
  border: 1px solid #000; /* borderを指定 */
  border-radius: 20px;    /* 角丸にする */
  text-align: center;     /* 文字を中央寄せ */
  margin-top: auto;       /* 【重要】上に取れるだけの余白 */
}

解説

まず各要素をフレックスボックスにして、flex-direction: column;を指定し、liの中の要素を縦並びにする。
そして、下揃えにしたい最後の要素に対して、margin-top: auto;を指定することで、最大余白を自動で取得するので、それ以外の要素の高さに依存せずに下揃えにすることが可能になります。

まとめ

CSSの様々な組み合わせで、まだまだ知らない組み方が出るのでコーディングは本当に奥が深いし面白いなと思います。
日々精進あるのみです。

おそまつ!

~ Qiitaで毎日投稿中!! ~
【初心者向け】HTML・CSSのちょいテク詰め合わせ

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1