flexを使用して、コンテンツを並べるときにjustify-content: space-between;を使用すると、二段目以降が左寄せで並ばないと、イライラしたことがあるかと思います。
よく、flexの子要素に疑似要素::afterをつけて回避がありますが、それとは別の方法をご紹介したいと思います。
動作サンプルは、ブラウザ幅が768px以上の時に、コンテンツ間のmarginを10px維持する並べ方です。また、二段目以降もかならず左寄せになります。
<html>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/common.css">
<title>デモ</title>
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<!--header-->
<header></header>
<main ontouchstart="">
<div class="backgroundBox">
<div class="Container">
<p class="start">justify-content: start;</p>
<div class="box-flex">
<div class="item">
<p>タイトル</p>
<p>コンテンツ</p>
</div>
<div class="item">
<p>タイトル</p>
<p>コンテンツ</p>
</div>
<div class="item">
<p>タイトル</p>
<p>コンテンツ</p>
</div>
<div class="item">
<p>タイトル</p>
<p>コンテンツ</p>
</div>
<div class="item">
<p>タイトル</p>
<p>コンテンツ</p>
</div>
</div>
</div>
</div>
</main>
<!--footer-->
<footer></footer>
</body>
</html>
<css>
* {
margin: 0;
padding: 0; }
html {
font-size: 62.5%;
-webkit-box-sizing: border-box;
box-sizing: border-box; }
.backgroundBox {
background-color: #9e9e9e66; }
.Container {
max-width: 980px;
margin: 0 auto 50px;
padding-top: 30px;
padding-bottom: 50px;
padding-right: 10px;
padding-left: 10px; }
.start {
font-size: 2.5rem; }
.space {
font-size: 2.5rem; }
/*justify-content: start;*/
@media screen and (min-width: 768px) {
.box-flex {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap; } }
.item {
height: 150px;
color: white;
background-color: #5555dc;
margin-bottom: 10px; }
@media screen and (min-width: 768px) {
.item {
-webkit-flex-basis: calc(calc(100% - 20px) / 3);
-ms-flex-preferred-size: calc(calc(100% - 20px) / 3);
flex-basis: calc(calc(100% - 20px) / 3); }
.item:not(:nth-child(3n)) {
margin-right: 10px; } }
<ポイント>
・justify-content: start;を指定
・flexの子要素にはflex-basisiにcalcを使用して、マージン幅を確保します。
100% – 20px ⇒flexを適用する親要素の幅内で、確保したいmarginの合計値を決める。今回は20px。
・flex子要素にmarginを指定する。今回は横に3つ要素を並べるので、3番目の要素にはmarginを適用しない。⇒:notを使用して3の倍数以外の要素にmarginを適用している。1番目と2番目の要素にmargin-right、10px指定しているので、margin合計値は20px。
すごく説明しにくいので、サンプル見て動かしてみてください。
今回は以上です。