YouTubeみたいな動画やGoogleマップなどには、自分のブログなどに埋め込んで利用できる機能がありますね。
そういった場合、ほとんど、iframeというものを利用して提供されています。
iframeの中にあるコンテンツは、自分のブログとは違うドメイン、違うサーバーで動いていますので、サイズの切り替えは難しいと思われがちですから、スタイルシートで手軽にレスポンシブ化させる方法をご紹介します。
※Googleアドセンスは、iframeの中に入れると規約違反になりますので、注意してください。
iframeをレスポンシブで表示したい時の、CSSの記述方法です。
たとえば、普通のiframeをクラス名(ここではiframe-responsive)で囲みます。
<div class="iframe-responsive"> <iframe width="560" height="315" src="https://www.youtube.com/embed/xqviGwyy7y0?rel=0" frameborder="0" class="iframe"></iframe> </div>
CSSに以下を追加します。
@media screen and (max-width: 560px) {
.iframe-responsive {
position: relative;
width: 100%;
padding: calc(315 / 560 * 100%) 0 0;
}
.iframe-responsive iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
これで、縦横の比率を保ちながら、伸縮します。
CSSの中の、315と560は、元のサイズの比率を計算させるために入れています。
max-width: 560pxは、もともとのiframeのサイズです。
ここの数値は、適時、変更しつつ使ってください。
あるいは、
HTMLとCSSを以下のようにしても。
<div class="iframe-responsive2" style="padding-top:56.25%;"> <iframe width="560" height="315" src="https://www.youtube.com/embed/xqviGwyy7y0?rel=0" frameborder="0" class="iframe"></iframe> </div>
.iframe-responsive2 {
position: relative;
width: 100%;
}
.iframe-responsive2 iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
padding-top:56.25%という数字は、どこから来ているのかというと、高さの315ピクセルを横幅560ピクセルで割ります、315÷560=0.5625。この数字に100をかけ算して、56.25という数字を導きだします。
たとえば、Googleマップで地図をここに掲載したい時、Googleマップの中サイズは、600と400ですから、400÷600×100=66.66….なので、padding-topに66.66%と記入します。
iframeでGoogleマップを設置する例
サンプルソースはこちら。
<style type="text/css">
.iframe-responsive2 {
position: relative;
width: 100%;
}
.iframe-responsive2 iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
<body>
<div class="iframe-responsive2" style="padding-top:66.66%;">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d12964.18096554228!2d139.744858!3d35.675888!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x48c7d4fa5e528690!2z5Zu95Lya6K2w5LqL5aCC!5e0!3m2!1sja!2sjp!4v1479287526858" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe></div>
</body>
