LoginSignup
0
2

More than 3 years have passed since last update.

[CSS]background-size:cover;とbackground-size:contain;の違いとポイント

Last updated at Posted at 2020-11-18

background-size:cover;

デザイン > 画像情報

画像が全て入らなくてもいいので、余白なく背景を画像で埋めたいときに使用。
余白を埋めるために画像を伸ばすのではなく、等比率で伸縮。

スクリーンショット 2020-11-18 11.14.09.png

background-size:contain;

画像情報 > デザイン

背景色が見えてもいいので、画像が切れることなく全体を見せたいときに使用。
画像全体を見せるための伸縮は等比率。

スクリーンショット 2020-11-18 11.17.18.png
※水色は余白

上記のようなレイアウトにするには以下3つの注意が必要
1. 余白は親要素の背景色が表示されるので、親要素にbackground-color:xxxx;が必要
2. background-repeat: no-repeat;を入れないと余白を埋めるために画像が繰り返され変な感じになる
3. 画像をセンタリングするためにbackground-position:center;が必要

ソースコード

<!-- 画像部分のみ抽出 -->

<!-- coverの方 -->
<div class="card__picture">
   <div class="card__imge card__imge--1"></div>
</div>                                             

<!-- containの方 -->                 
<div class="card__picture">
   <div class="card__imge card__imge--2"></div>
</div>             
/* ------- 画像 スタイル ------- */

/* サイズと背景色 */
.card__picture{
    width: 500px;
    height: 250px;
    background-color: aquamarine; 
}

/* センタリングと繰り返しなし */
.card__imge{
    height: inherit;
    background-position:center;
    background-repeat: no-repeat;
}

/* 各設置画像とsizeの設定 */
.card__imge--1{
    background-image: url(../img/coverSample.jpg);
    background-size: cover;

}
.card__imge--2{
    background-image: url(../img/containSample.jpg);
    background-size: contain;    
}

参考記事

https://gimmicklog.com/css3/747/
https://developer.mozilla.org/ja/docs/Web/CSS/background-size

次回

[CSS]画像の上に単色フィルター

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