1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CSS(SCSS) で Windows/Apple/iPhone/iPad/Macintosh/Chrome/Safari/Firefox/Edge/... などの分岐を仕込む手口のメモ

Last updated at Posted at 2022-09-23

解決したいこと

  • XXXX環境だとスクロールバーが出ないので grid がズレる💀
  • XXXX環境だと flex で中央に寄せてるはずなのに下にズレる💀

などなどそういうやつらにチームのデザイナーさんやコーダーさんが時間と精神力を無駄に浪費して死んでしまう事態💀

やること

ユーザーが視認するより前に動きそうな辺りで script で分岐に必用な環境判定処理を行い documentElementclassList にぶちこむ。力こそパワー!💪

 // ⇩ 実際には必用な分岐だけ設置すれば十分です。
 if (navigator.userAgent.match(/Chrome/))
  document.documentElement.classList.add('device-Chrome');
 else if (navigator.userAgent.match(/Safari/))
  document.documentElement.classList.add('device-Safari');
 else if (navigator.userAgent.match(/Firefox/))
  document.documentElement.classList.add('device-Firefox');
 else if (navigator.userAgent.match(/Edg/))
  document.documentElement.classList.add('device-Edge');
 if (navigator.userAgent.match(/Windows/))
  document.documentElement.classList.add('device-Windows');
 if (navigator.userAgent.match(/Linux/))
  document.documentElement.classList.add('device-Linux');
 if (navigator.userAgent.match(/iPhone/))
  document.documentElement.classList.add('device-iPhone', 'device-Apple');
 if (navigator.userAgent.match(/iPad/))
  document.documentElement.classList.add('device-iPad', 'device-Apple');
 if (navigator.userAgent.match(/Macintosh/))
  document.documentElement.classList.add('device-Macintosh', 'device-Apple');
 if (navigator.userAgent.match(/Android.+Mobile/))
  document.documentElement.classList.add('device-Android', 'device-Android-Mobile');
 else if (navigator.userAgent.match(/Android/))
  document.documentElement.classList.add('device-Android');

⇨ CSS(SCSS) で簡単に分岐できる

.some-selector {
 width: 10em;
 // SCSS の後置き & を使う (pure な CSS なら親要素側から素直に書く)
 html.device-Safari & {
  width: 11em;
 }
}

参考

なお…

本来はこのような仕込み分岐の要らないキレイなCSS1つであらゆる環境でデザイナーとユーザーの期待通りに動作してくれる事が望ましいし、あまりこうした本来仕様にない分岐を外から注入すべきではないのは言うまでもありません。わかった上で使いましょう…。悲しみ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?