Skip to content

解決 safari mobile 上 css 數值 "vh" 的問題 #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
JeffKko opened this issue Jan 19, 2021 · 2 comments
Open

解決 safari mobile 上 css 數值 "vh" 的問題 #14

JeffKko opened this issue Jan 19, 2021 · 2 comments

Comments

@JeffKko
Copy link
Owner

JeffKko commented Jan 19, 2021

Preface

最近發現在 safari mobile 上面展開一個 position: fixed; height: 80vh; 的 panel,
和其他瀏覽器相比, 高度明顯高於 80vh

這是在 chrome mobile 的畫面

image

這是 safari mobile (no address bar)

image

safari mobile (with address bar)

image

估狗了一下發現這是很多人都會遇到的問題

其實一張圖就可以完美詮釋這個問題

image

並且 Apple Safari Team 針對這個問題, 帥氣的回覆了:

It’s not a bug, it’s a feature.

好吧 既然是個 feature, 我們就來實做一個 feature

Try to solve

如果是為了 height: 100vh;

有一個非常單純的解法 height: -webkit-fill-available;

update: chrome v84以後 似乎已經不支援 -webkit-fill-available

如果不是 100vh 可以使用以下 css variables 的解法

css:

:root {
  --vh: 1vh;
}
function setCorrectViewHeight() {
  const windowsVH = window.innerHeight / 100
  document.documentElement.style.setProperty('--vh', windowsVH + 'px')
}

export default function safariHacks() {
  setCorrectViewHeight()
  window.addEventListener('resize', setCorrectViewHeight)
}

在適當的時候 import 這兩支 css 和 js 既可

然後在需要用到 vh 的時候這樣用就可以了

max-height: 80vh;
max-height: calc(var(--vh) * 80);

完成!

Reference Articles

@JohnYang02182
Copy link

JohnYang02182 commented Jan 24, 2022

您好,感謝 JeffKko 針對 safari 提供這麼棒的解法,但最近遇到一些問題想向 JeffKko 請教一下,關於這個解法是不是對 iphone 13 與 iphone 10 不會生效 ? 最近在執行專案時,用了這個方法,除了上述兩個版本的手機外,其他版本的 iphone 皆為正常。不知道 JeffKko 大大是不是也有同樣的問題 ?
ps 如果之後有更進一步的發現,也會再後面接著更新。

@toFrankie
Copy link

针对 -webkit-fill-available 不兼容最新 Chrome 的问题,可以类似这样处理:

body {
  min-height: 100vh;
}

@supports (-webkit-touch-callout: none) {
  body {
    min-height: -webkit-fill-available;
  }
}

当然这种方案,没办法处理类似 height: 90vhheight: calc(100vh - 50px) 等情况。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants