LoginSignup
3
1

More than 5 years have passed since last update.

iframeのアスペクト比を保持するメモ

Last updated at Posted at 2019-02-13

<img>タグなどは元来の縦横比を保持するために

img{
    width:100%;
    height:auto;
}

このように、heightにauto値を指定することによって、widthの値に対応し、縦横比を保持しながら、heightを自動調整するように設定できる。

しかし、<iframe>タグはwidthとheightにauto値を指定することができない(指定したら既定値に設定される)。
そのため、widthとheightを対応させられず、簡単に縦横比を保持することができない。

解決策

heightの値が0の<div>タグで<iframe>タグを包含し、<div>タグのpaddingに保持したい縦横比に対応した値を「%」で指定する。
paddingの値を%指定すると、paddingの値が親要素のwidthに対応して調整されるようになる。
例えば、<iframe>のwidthとheightがそれぞれ100と20、つまり5:1の縦横比だった場合、

.iframe-wrapper{
    height:0;
    padding-bottom:20%;
    position:relative;

}

iframe{
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}

このように指定すれば、<div>のpaddingは、その親要素のwidth*0.2の値を維持してくれる。
ただし、あくまでheight=0の「heightもどき」。包含している<iframe>が表示されなくなる。
なので、上記のように<iframe>を<div>に対して絶対位置指定させる必要がある。
positionの説明はめんどくさいから書かない。

間違いなどあればご指摘ください。無知なのでお願いします。

3
1
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
3
1