Flexboxのjustify-contentの基本的な使い方を紹介します。
Flexboxでのjustify-content
Flexboxは、要素を一次元のフレックスコンテナ内で効果的に配置するための方法を提供します。以下は、justify-contentプロパティの一部の使い方です。
.container {
display: flex;
justify-content: space-between;
}
このコードは、.container内のフレックスアイテムをコンテナの両端に均等に配置します。他にも、flex-start、flex-end、center、space-betweenなどが利用可能です。
サンプル
flex-start: 開始位置に寄せる
/* flex-start: 開始位置に寄せる */
.container.start {
justify-content: flex-start;
}
1
2
3
flex-end: 終了位置に寄せる
/* flex-end: 終了位置に寄せる */
.container.end {
justify-content: flex-end;
}
1
2
3
center: 中央に配置
/* center: 中央に配置 */
.container.center {
justify-content: center;
}
1
2
3
space-between: コンテンツの間に均等なスペースを挿入
/* space-between: コンテンツの間に均等なスペースを挿入 */
.container.between {
justify-content: space-between;
}
1
2
3
space-around: コンテンツの周りに均等なスペースを挿入
/* space-around: コンテンツの周りに均等なスペースを挿入 */
.container.around {
justify-content: space-around;
}
1
2
3
space-evenly: コンテンツの間と周りに均等なスペースを挿入
/* space-evenly: コンテンツの間と周りに均等なスペースを挿入 */
.container.evenly {
justify-content: space-evenly;
}
1
2
3
Gridでのjustify-content
Gridレイアウトも同様に、justify-contentを使用してコンテンツを水平方向に配置できます。以下は、Gridコンテナの例です。
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
justify-content: space-around;
}
この例では、.container内のgridアイテムを水平方向に均等に配置し、間にスペースを追加します。
よくある質問(FAQ)
Q. CSSのjustify-contentの値にはどんなものがありますか?
A. flex-start(先頭詰め)・flex-end(末尾詰め)・center(中央)・space-between(両端揃え)・space-around(等間隔)・space-evenly(均等間隔)があります。
Q. space-betweenとspace-aroundとspace-evenlyの違いは?
A. space-betweenは両端の要素を端に配置して間を均等に分割、space-aroundは各要素の両側に等しいスペースを追加、space-evenlyは全ての間隔(端を含む)を完全に均等にします。
Q. justify-contentはGrid Layoutでも使えますか?
A. はい。display: gridの場合はjustify-contentでグリッドトラック全体の水平配置を制御できます。Gridではjustify-items(各セルのアイテム配置)とjustify-self(個別アイテム)も使えます。