0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

メディアを、スマホの時にタイトル→画像→テキストの順に並べたい

Posted at

やりたいこと

これを
image.png

スマホの時はこうしたい
image.png

コードはこんな感じ。

            <div class="media">
                <figure class="media__image">
                    <img src="hogehoge.jpg" alt="">
                </figure>
                <div class="media__body">
                    <h2 class="media__title">タイトル</h2>
                    <p class="media__text">hogehoge</p>
                </div><!-- /.media__body -->
            </div><!-- /.media -->
.media {
    display: flex;
}

.media__image {
    width: 30%;
}

問題点

タイトルより画像の方が上に来るのならば、flex-directionを指定するだけでよいので問題ない。ただし今回の場合は画像が.media__bodyの中に割り込む形になるため少し悩んだ。

解決策

display:contentsを使ってみる

display:contentsはそのタグ自体の存在をないもののように扱えるみたい。(厳密には違うのかもしれないけど)

@media (max-width:700px) {
    .media {
        flex-direction: column;
    }
    .media__body {
        display: contents;
    }
    .media__title {
        order: -1;
    }
}

こうすることによって、htmlの方がこんなイメージになるのかな

            <div class="media">
                <figure class="media__image">
                    <img src="hogehoge.jpg" alt="">
                </figure>
               <!-- 下の2つを囲んでいた.media__bodyが存在しないような振る舞いになる -->
                <h2 class="media__title">タイトル</h2>
                <p class="media__text">hogehoge</p>
            </div><!-- /.media -->

あとはorderで順番を変えれば良い。

これってどうなのって話

見た目通りにはなるけど、普段あまり使わない display:contents を使っていいのかなっていうのがある。ブラウザごとに挙動が違ったりしないかな

(↑ 対応してないものもいくつかある)

gridを使うっていうのも見かけるけど、それってタイトルが長くなったりした時もしっかり機能するの?

何かいい組み方があったら教えてください!!

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?