これは知っておくと便利なテクニック! CSSだけでスクリーンの幅と高さ、さらには要素の幅と高さの値を取得する方法
Post on:2025年10月28日
sponsorsr
JavaScriptは使用せずに、シンプルなCSSだけでスクリーンの幅と高さ、さらには任意の要素の幅と高さの値を取得する方法を紹介します。
取得する値は単位のない値なので、CSSのあらゆる数式で再利用できます。

まずはスクリーンの幅と高さの値を取得するデモページをご覧ください。
See the Pen
Screen width/height (CSS-only) by coliss (@coliss)
on CodePen.
このCSSで取得できる値は厳密に言うと、ビューポートのサイズです。そのためスマホのように幅と高さいっぱいで表示するような環境であれば、スクリーンのサイズと同義になります。デスクトップの場合はブラウザをフルスクリーンで表示した際にそうなります。
下記のシンプルなCSSでスクリーンの幅と高さの値を取得できます。
|
1 2 3 4 |
:root { --w: calc(100vw/1px); --h: calc(100vh/1px); } |
--wはスクリーンの幅、--hはスクリーンの高さで、取得した値は単位のない整数値です。--wと--hはCSSの中で自由に再利用できます。
さらに、こちらのCSSを使うと任意の要素の幅と高さを取得できます。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@property --_w { syntax: '<length>'; inherits: true; initial-value: 100vw; } @property --_h { syntax: '<length>'; inherits: true; initial-value: 100vh; } :root { --w: tan(atan2(var(--_w),1px)); --h: tan(atan2(var(--_h),1px)); } |
CSSの@propertyやtan()などがサポートされている環境には、こちらの方が便利です。
もちろん、スクリーンの幅と高さの値を取得することもできます。
See the Pen
Screen width/height (CSS-only) by coliss (@coliss)
on CodePen.
@propertyについて詳しくは、下記をご覧ください。
元ネタは下記ポストより。
Getting the screen dimension with a simple calc? Yes, it's possible!https://t.co/37mZoQnVuI
We are still waiting for Firefox to join the game, and the code below will become the favorite one of many developers!
(Until then, there is another method with better support) pic.twitter.com/TOVUn0qTI0
— CSS by T. Afif (@ChallengesCss) October 24, 2025
sponsors











