縦横比を保って背景画像を拡大縮小する

by uto usui

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>

<h1 class="h1 font-weight-bold text-xs-center text-capitalize">responsive background image cats</h1>

<div class="wrap">
  <div class="inner">
    <div class="img-box"></div>
    <div class="img-box"></div>
    <div class="img-box"></div>
  </div>
</div>

SCSS

body {
  font-family: 'Dancing Script', cursive;
  background-image: linear-gradient(45deg, #F7CAC9 15%, #91A8D0 85%);
}

.h1 {
  margin: 1em;
  color: rgba(white, .85);
}

.wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  
}

.inner {
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-flow: wrap;
  justify-content: center;
  align-items: center;
}

.img-box {
  height: 0;
  margin: 15px;
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  &:nth-child(1) {
    width: 100%;
    padding-top: calc(900 / 1200 * 100%);
    background-image: url('http://placekitten.com/1200/900');
  }
  &:nth-child(2) {
    width: 80%;
    padding-top: calc(300 / 700 * 80%);
    background-image: url('http://placekitten.com/700/300');
  }
  &:nth-child(3) {
    width: 120%;
    padding-top: calc(500 / 1200 * 120%);
    background-image: url('http://placekitten.com/1200/500');
  }
}

JavaScript

WebFontConfig = {
    google: { families: [ 'Dancing+Script:400,700:latin' ] }
  };
  (function() {
    var wf = document.createElement('script');
    wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
  })();