レスポンシブ対応時便利な背景画像サイズを変更する実装方法

レスポンシブ対応時便利な背景画像サイズを変更する実装方法

LPでよく使う可変する背景画像の実装方法

端末サイズに合わせて背景画像を同じ比率で拡大縮小させていく実装方法をまとめました。
レスポンシブ対応のLPなどのメインビジュアル作成時に便利だと思います。

実装要件
・SPメインのLPだけどPCにも対応させておきたい
・メインビジュアル内のテキスト要素はHTML側で実装する

デモサイトはこちら

DEMO

HTML

<div class="wrapper">
    <div class="main-img">
        <div class="main-img__box">
            <div class="main-img__ribbon">家族旅行におすすめ</div>
            <h1 class="main-img__title">人気ランキングトップ10</h1>
        </div>
    </div>
</div>

 

CSS

.main-img {
  position: relative;
  background-image: url("../img/bg_img.jpg");
  background-repeat: no-repeat;
  background-size: 100% auto;
}
.main-img:after {
  display: block;
  padding-top: calc((140 / 375) * 100%);
  content: '';
}
.main-img__box {
  margin: 0 auto;
  padding: 15px 5px;
  position: absolute;
  width: 90%;
  top: 8%;
  right: 0;
  left: 0;
  background-color: rgba(255,255,255,0.7);
  text-align: center;
  line-height: 1.3;
}
.main-img__ribbon {
  display: inline-block;
  margin-bottom: 10px;
  width: 200px;
  position: relative;
  color: #fff;
  background-color: #f2bb45;
  text-align: center;
  line-height: 28px;
  font-size: 13px;
}
.main-img__ribbon:before,
.main-img__ribbon:after {
  position: absolute;
  z-index: 1;
  content: '';
}
.main-img__ribbon:before {
  left: -8px;
  border: 20px solid #f2bb45;
  border-width: 14px 8px 14px;
  border-left-color: transparent;
}
.main-img__ribbon:after {
  right: -8px;
  border: 20px solid #f2bb45;
  border-width: 14px 8px 14px;
  border-right-color: transparent;
}
.main-img__title {
  color: #333;
  font-size: 22px;
}
/* pc用 */
@media screen and (min-width: 961px) {
    .main-img{
      width: 960px;
      margin: 0 auto;
  }
    .main-img__box{
      width: 600px;
      top: 25%;
      padding: 25px 5px;
  }
    .main-img__ribbon {
      display: inline-block;
      margin-bottom: 15px;
      width: 300px;
      line-height: 32px;
      font-size: 18px;
  }
    .main-img__ribbon:before {
      left: -8px;
      border: 20px solid #f2bb45;
      border-width: 16px 8px 16px;
      border-left-color: transparent;
  }
    .main-img__ribbon:after {
      right: -8px;
      border: 20px solid #f2bb45;
      border-width: 16px 8px 16px;
      border-right-color: transparent;
  }
    .main-img__title {
      color: #333;
      font-size: 28px;
  }
}

今回大事な箇所は、背景画像を比率を保ちながら可変して実装するところですね。
divタグ.main-imgで背景画像を指定して背景サイズを横幅100%になるようにしています。
そこに.main-img:afterの擬似要素内のpadding-topで画像比率分のサイズを確保して表示させています。
擬似要素なのでcontent: ‘ ‘;はお忘れなく。
今回は375pxのスマホ端末で表示した時に、高さ140pxで表示される分の高さを確保しました。
padding-top: calc((140 / 375) * 100%);
ここの数字を変えればOKです!
calc() 関数は、1つの式を引数として取り式の結果が値として使用できるのでレスポンシブのマークアップではかかせません!

メインビジュアル内の文字はすべてHTML側で変更できるようにしてあります。
テキスト打ちだと味気ない場合は、DEMOサイトのようにリボン型の帯をつけるなど少し装飾をするだけで華やかになりますね👍
キャンペーンの掲載期間を更新していく必要があったり、年月日の更新があるLP作成などの場合はテキスト部分はHTML側に実装しておくと更新時助かります😊
ぜひお試しください!

 

サイト制作カテゴリの最新記事