![見出し画像](https://assets.st-note.com/production/uploads/images/51167418/rectangle_large_type_2_e57ab4884b689d78487115d72d6059b4.png?width=1200)
レスポンシブに役立つCSS(2)Youtube(iframe)の比率を保つ。
巷に溢れてますが、直感的にわかりずらいので書きます。htmlまるっとコピーして使えます。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>CodingSample/Youtubeレスポンシブ</title>
<style type="text/css">
body, html {
/*ウインドウの余白をなくす*/
margin: 0;
padding: 0;
}
* { /*全て*/
box-sizing: border-box; /*線は内側に引く*/
}
.youtubeSize {
width: 80%; /*youtubeSizeの親要素に対しての幅*/
margin: 0 auto; /*左右センター(なくても良い)*/
}
.youtubeSize .Box {
/*youtubeSizeの中のBoxは*/
width: 100%; /*youtubeSizeに対して幅いっぱい*/
padding-bottom: 56.25%; /*youtubeの比率は16:9固定。比率16/9=0.5625*/
position: relative; /*子要素(iframe)に受け継ぐ*/
}
.youtubeSize .Box iframe {
position: absolute; /*Box(親要素)内の絶対位置*/
width: 100%!important; /*Box(親要素)に対して100%の幅*/
height: 100%!important; /*Box(親要素)に対して100%の高さ*/
/*!important/iframeで指定されているwidth/heigihit余地もこちらを優先*/
}
</style>
</head>
<body>
<div class="youtubeSize">
<div class="Box">
<iframe width="560" height="315" src="https://www.youtube.com/embed/Qp3b-RXtz4w" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
</body>
</html>
これで十分なんだが、仕事的にもっと汎用性のあるものに改良したい。ここのところずっと思案中。
よろしければ「スキ」をお願いしますm(_ _)m