LoginSignup
4
2

More than 5 years have passed since last update.

CSSのみで縦横比固定の要素をウインドウサイズいっぱいに表示する

Posted at

ウインドウサイズによらず縦横比固定で表示したいケースがある。
JavaScriptを使う方法もあるが、CSSのみで実現する。

コード例(縦横比 16:9)

<div class="content"></div>
body {
  margin: 0;
}

.content {
  background-color: green;
  height: 56.25vw;
  width: 177.78vh;
  max-height: 100vh;
  max-width: 100vw;
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

Demo(JSFiddle)

ポイント

  • heightvwwidthvhで指定することにより縦横比を固定
    • 上の16:9の例では、heightは(9 / 16 * 100 = 56.25)、widthは(16 / 9 * 100 ≒ 177.78)
  • max-heightmax-widthを指定し、画面外に要素がはみ出さないようにする
  • positionabsolutemarginautoにし、4つの配置位置をそれぞれ0にすることで、画面中央に配置する
4
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
4
2