LoginSignup
21
17

More than 5 years have passed since last update.

Flexboxで横並びにした画像と、複数行(段落)のテキストを背景色引き伸ばしつつ上下中心にもってくる

Last updated at Posted at 2017-03-14

こういうことがしたい

説明がややこしいけど、こういうことがしたかったのです。

img01.png

  • Flexboxの横並びで上下左右中央
  • 片方は画像、片方は段落のあるテキスト
  • 幅はそれぞれ50%で幅・高さ可変、レスポンシブ
  • 背景色も画像の高さに合わせて全体に伸ばしたい

この複数の段落があるテキスト部分を、 Flexboxで背景も可変に引き伸ばしつつ上下中央に綺麗にもってきたい!
解決したのでメモとして残しておきますー

もしテキスト部分が一行なら…

テキスト部分が一行(pタグ一個だけとか)なら、上下中心にもってくるのは簡単。
横並びしている、上下中心にもってきたい子要素の方にもdisplay: flex;をかけて、尚且つalign-items:center;をその子要素にだけつければOK。

複数段落になるとそれだけじゃうまく中心にならない

複数の段落がある場合、上記の方法だとそれぞれの段落で上下均等に余白ができてしまうのでなんか気持ち悪いことになります。こんなかんじ。

img02.png

解決策

簡単でした、、。
要は中の段落がそれぞれバラけて中央配置になるのを防ぐために、そいつらをdivでさらに囲んであげればいいだけです。
ざっくり完成コードこちら。
※リセットなど基本的なスタイルは省略しています

html
<div class="type1">
    <p class="img"><img src="hoge1.png"></p>
    <div class="txtwrap">
        <!-- ここにdivをひとつ追加 -->
        <div>
            <h2>小見出し的なタイトル</h2>
            <p>テキストテキストテキストテキストテキスト<br>
            テキストテキストテキストテキストテキスト<br>
            テキストテキストテキストテキストテキスト</p>
        </div>
    </div>
</div>
<div class="type2">
    <p class="img"><img src="hoge2.png"></p>
    <div class="txtwrap">
        <div>
            <h2>小見出し的なタイトル</h2>
            <p>テキストテキストテキストテキストテキスト<br>
            テキストテキストテキストテキストテキスト<br>
            テキストテキストテキストテキストテキスト</p>
        </div>
    </div>
</div>
<div class="type1">
    <p class="img"><img src="hoge3.png"></p>
    <div class="txtwrap">
        <div>
            <h2>小見出し的なタイトル</h2>
            <p>テキストテキストテキストテキストテキスト<br>
            テキストテキストテキストテキストテキスト<br>
            テキストテキストテキストテキストテキスト</p>
        </div>
    </div>
</div>
scss
.type1,.type2{
  display: flex;
  -webkit-flex-wrap: wrap;
      -ms-flex-wrap: wrap;
          flex-wrap: wrap;
}
.type2{
  -webkit-flex-direction: row-reverse;
      -ms-flex-direction: row-reverse;
          flex-direction: row-reverse;
}
.img{
  width: 50%;
  img{
    width: 100%;
  }
}
.txtwrap{
  background: #ccc;
  width: 50%;
  display: flex;
  -webkit-align-items: center;
          align-items: center; //上下中心にする
  -webkit-justify-content: center;
          justify-content: center; //左右中心にする
  div{
    text-align: left;
  }
}

以上メモでした

21
17
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
21
17