LoginSignup
14
6

More than 3 years have passed since last update.

flexboxの親要素を可変の子要素に合わせるCSS

Last updated at Posted at 2020-02-02

Flexboxで作成した場合、親要素は横幅100%となります。
子要素をinline表示とし、親要素幅を子要素に合わせたい場合のCSS設定をメモしておきます。

どんな状態か、デモをご確認ください。

デモ

子要素に合わせて親要素を横幅可変

See the Pen 親要素の横幅100% by harumi-sato (@harumi-sato) on CodePen.

子要素に関係なく親要素を横幅100%固定

See the Pen 親要素の横幅、子要素のサイズに可変 by harumi-sato (@harumi-sato) on CodePen.

コード

Flexboxを囲ったblockに inline-blockを指定すると、
子要素がinline-blockの振る舞いとなります:thumbsup:

HTML
<div class="parent">
<ul class="item_parent">
<li class="item_child _child1">category1</li>
<li class="item_child _child2">category2</li>
</ul>
</div>
CSS
.parent{
  display:inline-block;
}
.item_parent{
  display:flex;
  background:lightpink;
}
.item_child{
  background:#fff;
}

まとめ

親要素が可変する場合、1段上に幅指定用のブロックを作成する。

14
6
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
14
6