こんにちは!
今回はCSSのdisplay: inline-flexについてまとめます。
display: inline-flexとは?
- flexコンテナを定義するが、コンテナ自体はinline要素のように横に要素を並べられる
- 見出しなどで便利
やりたいこと
- タイトルの前に正方形、中央揃えで数字を入れたい
コード例
<h1 class="title"><span class="title_number">1</span>Lorem ipsum</h1>
.title { font-size: 30px; } .title_number { background-color: antiquewhite; width: 50px; height: 50px; }
display: inline-blockの場合
.title_number { background-color: antiquewhite; width: 50px; height: 50px; display: inline-block; text-align: center; line-height: 50px; }
- 横と縦の指定が出来るように、
display: inline-block
を指定 text_align
とline-height
で上下中央揃え
難点
height
が変更になった際に、上下中央揃えにするためにはline-height
も変更が必要
display: inline-flexの場合
.title_number { background-color: antiquewhite; width: 50px; height: 50px; display: inline-flex; justify-content: center; align-items: center; }
display: inline-block
でflexコンテナ化しつつ、右側にタイトルが並ぶように- 上下中央揃えは
align-items
で行っているので、height
が変更になっても調整不要
display: flexの場合
.title_number { background-color: antiquewhite; width: 50px; height: 50px; display: flex; justify-content: center; align-items: center; }
display: flex
の場合は、flexコンテナ化できるが、自身がブロック要素になるのでタイトルが右に並ばない- 数字とタイトルを並べるためには、数字とタイトルを囲むdivを作成し、さらにflexコンテナで囲まないといけない
おわりに
今回はCSSのdisplay: inline-flexについてまとめました。実はまだ使ったことがないプロパティですが、変更に強く、div要素を減らせそうなのでこれから使っていきたいと思います。
93/100