LoginSignup
130
119

More than 5 years have passed since last update.

flexboxで上下左右中央揃え

Last updated at Posted at 2016-10-19

目的

  • こんな感じの配置がしたい

名称未設定.png

コード

vertical-center.html
<div class="flexbox-container-vertical-center">
    <span>中央</span>
</div>
vertical-center.css
.flexbox-container-vertical-center {
    display: flex; /* 子要素をflexboxで揃える */
    flex-direction: column; /* 子要素をflexboxにより縦方向に揃える */
    justify-content: center; /* 子要素をflexboxにより中央に配置する */
    align-items: center;  /* 子要素をflexboxにより中央に配置する */
    width: 100px; /* 見た目用 */
    height: 50px; /* 見た目用 */
    border: 1px solid; /* 見た目用 */
}
span {
    border: 1px solid; /* 見た目用 */
}

実行結果

スクリーンショット 2016-10-19 17.58.43.png

できた。

解説

  • display: flex; を指定することでflexboxで操作可能となった 直下の子要素(この例ではspan要素)がflex-direction: column; を指定することで縦に並ぶようになる。
  • さらに、justify-content: center;で縦方向の中央、align-items: centerで横方向中央に位置づけるようにすれば、完成。

応用(?)装飾

  • チョットキレイにする

スクリーンショット 2016-10-19 20.10.07.png

vertical-center.css
.flexbox-container-vertical-center {
    display: flex; /* 変更なし */
    flex-direction: column; /* 変更なし */
    justify-content: center; /* 変更なし */
    align-items: center; /* 変更なし */
    width: 100px; /* 変更なし */
    height: 50px; /* 変更なし */
    border: 0 ; /* 見た目用 */
    border-radius: 50px; /* 見た目用 */
    background-color: coral; /* 見た目用 */
    box-shadow: 0px 1px 1px darkmagenta; /* 見た目用 */
    }
span {
    border: 0;
    color: white; /* 見た目用 */
}

その他

  • 「見た目用」とコメントアウトされいている箇所は、適当な数値でOKです。
  • 全体のCSSで.flexbox-container-vertical-center を定義しておくとらくちん。class="flexbox-container-vertical-center"とするだけで、 直下の子要素 をなんでも上下中央に配置できるので。

駄文

  • flexbox超便利。bootstrap3のグリッドレイアウトは、そのままつかうにはとてもお手軽でいいけど、少しでも外れたことをやろうとするなら、flexbox一択。
  • bootstrap4だとflexboxも使えるとあるけど、どういう意味なのかな。
130
119
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
130
119