

横並びコンテンツを左右反転させるにはどうすればいいの?
そんな疑問にお答えします。
画像とテキストを横並びにしたコンテンツを複数個並べる場合、奇数番目と偶数番目とで画像とテキストの配置を左右反転させるデザインはよく目にします。
左右反転させない場合と比較すると見やすいですね。
今回はこちらの実装方法を見ていきましょう。
偶数番目と奇数番目で画像の配置を左右反転させる方法
コード表示
先に全コードを貼っておきます。
あとで解説します。
<div class="hoge-item">
<div class="hoge-item-picture">
<img src="img/01.jpeg" alt="" />
</div>
<div class="hoge-item-body">
<p class="hoge-item-title">シベリアン・ハスキー</p>
<p class="hoge-item-text">テキスト内容</p>
</div>
</div>
<div class="hoge-item">
<div class="hoge-item-picture">
<img src="img/02.jpeg" alt="" />
</div>
<div class="hoge-item-body">
<p class="hoge-item-title">柴犬</p>
<p class="hoge-item-text">テキスト内容</p>
</div>
</div>
<div class="hoge-item">
<div class="hoge-item-picture">
<img src="img/03.jpeg" alt="" />
</div>
<div class="hoge-item-body">
<p class="hoge-item-title">ゴールデン・レトリバー</p>
<p class="hoge-item-text">テキスト内容</p>
</div>
</div>
hoge-item {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #e5e3d8;
padding: 60px;
}
.hoge-item:nth-child(even) {
flex-direction: row-reverse;
}
.hoge-item-picture {
width: 46%;
}
.hoge-item-picture img {
width: 100%;
height: auto;
}
.hoge-item-body {
width: 46%;
}
.hoge-item-title {
font-size: 24px;
font-weight: bold;
}
.hoge-item-text {
margin-top: 20px;
}
コード解説
.hoge-item:nth-child(even) {
flex-direction: row-reverse;
}
横並びにした画像とテキストを上下中央配置にするやり方はこちらをご覧ください。
今回のポイントは2つあります。
まずは flex-direction: row-reverse; です。
子要素をどの方向に配置していくかは「flex-direction」プロパティで指定します。
row(初期値)は子要素を左から右に配置します。(➡)
これを反転(⬅)させるには「row-reverse」を指定します。
もうひとつのポイントは :nth-child(even) です。
これは対象の要素が「親要素に含まれている子要素の中で何番目の子要素か」を示す疑似クラスです。
今回は偶数番目を左右反転させるので「:nth-child(even)」としています。
ここは「:nth-child(2n)」としても同じ結果になります。
ちなみに奇数番目を反転させるならば「:nth-child(odd)」もしくは「:nth-child(2n+1)」と指定します。
「even」と「odd」だとどちらが偶数でどちらが奇数かがわかりにくいかもしれません。
僕は「even」は4文字だから偶数、「odd」は3文字だから奇数と覚えました。
覚えるのが面倒なら「2n」「2n+1」を使っておけば間違えないですね。
💡左右反転させるポイント!
-
flex-direction: row-reverse;で右から左に並べる
-
:nth-child()で奇数番目、または偶数番目を指定
Flexboxは短いコードでもいろんなことができて奥が深いです。
どんどん使いこなしていきましょう。
以上です。
投稿者 トシ
コメントを残す