本記事では、displya:flexで横並びにした要素に対して均等に余白を設ける方法について解説しています。
HTML/CSSの学習におすすめ書籍
1冊ですべて身につくHTML&CSSとWebデザイン入門講座

メリット
- HTMLとCSSの基本が体系的に学べる
- Webデザインの基本が学べる
- 1つのWebサイトを作りながら学べる


Amazon Kindle Unlimitedに登録すると、月額980円で読み放題だからオススメだよ!



初回30日間は無料だから、まだ登録したことのない人はぜひ試してみてね!
全プログラマー必見!
変数名/関数名にもう悩まない!
変数名/関数名にもう悩まない!
リーダブルコード


メリット
- 美しいコードが書けるが自然と書けるようになる
- 他の開発者が理解しやすいコードになる
著:Dustin Boswell, 著:Trevor Foucher, 解説:須藤 功平, 翻訳:角 征典
¥2,640 (2023/07/23 02:48時点 | Amazon調べ)


目次
均等に余白を設ける2つの方法



先輩!均等に余白を設けるにはどうすればいいんですか?



2つの方法があるから、別々に紹介するね!個人的に1つ目に紹介するjustify-conentプロパティを使う方法がオススメだよ!
justify-conentプロパティで調整する
1つ目は、justify-conentプロパティを使った方法です。余白を設定できる値は3つあるため、最適な値を選びましょう。
.flex {
display: flex;
/* 3つの中から1つを選択 */
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;
}
- space-between:アイテム間同士の余白を設ける
- space-around:アイテム間同士の余白と外側に余白を設ける(1/2サイズ)
- space-evenly:アイテム間同士の余白と外側の余白を全て均等に設ける





背景色のグレーは設定した時に出る余白を表しているよ!
marginプロパティで調整する
2つ目は、marginプロパティで余白を設ける方法です。
CSSに慣れていない方だとフレックスアイテム全体に余白を付け、1番最初のアイテムだけ余白を0に戻すという書き方をしがちですが、隣接するクラスに適用させる「+」のワイルドカードを使うことで簡潔に記述することが出来ます。
/*
.flex:親要素(flexコンテナ)
.flex:子要素(flexアイテム)
*/
.flex {
display: flex;
}
.flex > .flex__item + .flex__item {
margin-left: 30px;
}





中央寄せしてから均等に余白を設けたい場合は、親要素に「justify-content: center;」を追加します!