【JavaScript】縦長 / 縦狭い スマホの画面比率(アスペクト比)でCSSクラスを自動判定・付与する方法
メディアクエリのアスペクト比は、ナビゲーション関係が考慮されない、縦のサイズぴったりになにかしたいとき用です。
WEBデザインの実装において、iPhone SEのような「短めの画面」から、最新Androidのような「縦長画面」まで、デバイスごとの画面比率(アスペクト比)の違いに頭を悩ませることはありませんか?
「メディアクエリの幅(width)だけでは、高さ方向のデザイン崩れが防げない……」
今回は、そんな時に役立つJavaScriptのTipsを紹介します。画面の縦横比を計算し、それに応じたCSSクラスを <body> に自動付与するユーティリティクラスの実装例です。
実装コード
以下の Media クラスを作成し、初期化関数を呼び出すだけで動作します。
export class Media {
static init() {
this.initMedia();
}
static initMedia() {
// 初期実行
this.updateSpClass();
// リサイズ・画面回転時に実行
window.addEventListener('resize', this.updateSpClass.bind(this));
window.addEventListener('orientationchange', this.updateSpClass.bind(this));
}
static updateSpClass() {
const BREAK_POINT = 768;
const w = window.innerWidth;
const h = window.innerHeight;
// 横画面(Landscape)または PCレイアウト(BREAK_POINT以上)は除外
const isLandscape = h < w;
const isNotSmartPhone = w > BREAK_POINT;
if (isLandscape || isNotSmartPhone) {
// クラスをリセットして終了
document.body.classList.remove('is-short-sp', 'is-long-sp');
return;
}
const ratio = w / h; // アスペクト比を計算
document.body.classList.remove('is-short-sp', 'is-long-sp');
// コンソールで現在の比率を確認可能
console.log("Current Aspect Ratio:", ratio);
// 数値はデバイスごとの実測値に基づいた閾値
if (ratio > 0.65) {
// 画面が短い端末(iPhone SEなど)
document.body.classList.add('is-short-sp');
} else if (ratio > 0.56) {
// 標準的な比率(多くのiPhoneシリーズ)
// 必要に応じてここに処理を追加
} else {
// 縦に長い端末(Androidのロングディスプレイなど)
document.body.classList.add('is-long-sp');
}
}
}