How to access the real 100vh on iOS in CSS — Stack Overflow

How to access the real 100vh on iOS in CSS - Stack Overflow Ipad

Addressing the ios address bar in 100vh layouts

As I deployed my first PSD conversion with its beautiful 100vh and 100vw hero image, I was horrified to discover that the bottom of my layout was hidden when viewed from my iPhone 6s iOS 10 Safari. Why? I thought I did everything right! Did I accidentally add margin or padding somewhere? What was I overlooking?

Upon closer inspection, I quickly realized that although my hero image was in fact 100vh, it was partially covered by Safari’s address and tool bar, creating the dreaded “wiggle-scroll”. That’s fine, I thought. Nothing a quick search on Google and Stack Overflow can’t fix. However, I learned that the solution isn’t quite so straightforward.

After doing some research, I realized it was a fairly common complaint, referred to by some as the “iOS viewport scroll bug”. In February of 2021, Nicolas Hoizey reported the bug on Webkit Bugzilla when he discovered the bottom of his 100vh mobile game was cut off by the browser buttons bar. Benjamin Poulain, an engineer at Apple replied to Hoizey . He stated — in true programmer fashion — that it wasn’t a bug, it’s a feature.

This is completely intentional. It took quite a bit of work on our part to achieve this effect. 🙂

The base problem is this: the visible area changes dynamically as you scroll. If we update the CSS viewport height accordingly, we need to update the layout during the scroll. Not only that looks like shit, but doing that at 60 FPS is practically impossible in most pages (60 FPS is the baseline framerate on iOS).

Читайте также:  Способы установки пароля на приложения в айфоне: как запаролить галерею, заметки

It is hard to show you the «looks like shit» part, but imagine as you scroll, the contents moves and what you want on screen is continuously shifting.

Dynamically updating the height was not working, we had a few choices: drop viewport units on iOS, match the document size like before iOS 8, use the small view size, use the large view size.

From the data we had, using the larger view size was the best compromise. Most website using viewport units were looking great most of the time.

I for one, am not an engineer at Apple, so I believe him when he says there are good reasons behind why they designed this behaviour. Thus, the bug was marked “RESOLVED WONTFIX”, and I realized I would have to delve deeper if I ever wanted my beautiful, 100vh hero image.

How to access the real 100vh on ios in css

Set a root CSS var like so in your stylesheet:

// CSS vars
:root { --real100vh: 100vh;
}

Then in JavaScript, on load (or jQuery ready) and on resize, you want to run this code:

 set100vhVar() { // If less than most tablets, set CSS var to window height. let value = "100vh" if (this.winWidth <= 1024) { value = `${window.innerHeight}px` } document.documentElement.style.setProperty("--real100vh", value) }

Now you can simply use the CSS: height: var(--real100vh); wherever you want 100vh to actually be the real 100vh on mobile, and this will simply work!

It looks better if you also add a transition: height 0.4s ease-in-out; on the same element, so it doesn’t snap when you scroll down on mobile.

The advantage of using a CSS var to do this is that you can override this whenever you like, for example you might want certain breakpoints to be height: 500px, and this is hard to do if you use an inline style. You can also use this inside calc(), like height: calc(var(real100vh) - 100px); which is useful for fixed headers.

Читайте также:  Как включить куки файлы на айфоне? — блог про компьютеры и их настройку

If you use Vue/Nuxt, take a look at how we have implemented that here.

Vh and vw units can cause issues on ios devices. to overcome this, create media queries that target the width, height, and orientation of ios devices.

Is anyone else having trouble targeting ipads currently (2021-2020)? I‘ve spent countless hours trying to fix blurry images on a particular page. I have the fix, and have successfully targeted my css to the iphone using two different methods, but can’t seem to target the ipad. I have tried targeting by width and by webkit-overflow-scrolling (which works on the iphone). I’m wondering if Apple’s change in September 2021 to have the ipad act as a desktop is affecting targeting by device width as above. Any thoughts? Thanks!!!

Задаем размер 100vh без прокрутки для мобильных устройств

Суть задачи будет понятна для тех, кто уже столкнулся с этой проблемой. Но попробую объяснить для всех, потому как рано или поздно пригодится.

Есть страница, высота которой 100vh – один экран без какой-либо прокрутки. На десктопе 100vh будут равны 100% высоты области просмотра и никакой прокрутки не будет. А вот на мобильном устройстве (почти на всех) 100vh будет равно 100% высоты экрана минус интерфейс браузера. И проблема возникает, когда вы начинаете прокручивать экран, интерфейс браузера (адресная строка или кнопки навигации) скрываются и происходит небольшой скачок содержимого страницы. Из-за этого получается ситуация, когда на мобильном при свайпе дергается экран.

Выглядит это примерно так:

alt

Для того, чтобы этой проблемы избежать используем JavaScript и CSS.

В JavaScript вы всегда можете получить значение текущей области просмотра с помощью глобальной переменной window.innerHeight. Это значение учитывает интерфейс браузера и обновляется при изменении его видимости. Хитрость заключается в том, чтобы сохранить значение области просмотра в переменной CSS и применить его к элементу, а не к единицам vh.

Допустим, --vh – это наша пользовательская переменная CSS для этого примера. И мы будем ее использовать в нашем CSS следующим образом:

Читайте также:  Джобс, Стив | Apple вики | Fandom

Теперь давайте получим внутреннюю высоту области просмотра в JavaScript:

Итак, мы получили высоту области видимости, а затем получили от нее 1/100, таким образом, у нас есть значение, которое нужно назначить в качестве значения единицы высоты нашего окна просмотра. Затем с помощью JS создаем переменную для CSS ( --vh) в :root.

С помощью JavaScript в ваш HTML к элементу <html> будет добавлено правило:

Где 8.12px – это 1/100 от высоты области видимости, и для каждого экрана это число будет разное.

В результате теперь мы можем использовать --vh в качестве единицы измерения высоты, как и любую другую vhединицу, умножив её на 100, и у нас будет полная высота, которую мы хотим.

По итогу, получим такой CSS:

Предусмотрим вариант, что экран устройства можно развернуть, и чтобы при ресайзе произошел перерасчет единиц измерения 1/100 высоты области просмотра, будем использовать такой JavaScript:

Внимание – могут быть проблемы в IE11 – еще не до конца разобрался, поэтому данную фичу имеет смысл использовать исключительно для мобильных устройств.

Пример работы 100%-ой высоты экрана для мобильных устройств:

See the Pen Viewport Height on Mobile (no resize on update) by Denis (@deniscreative) on CodePen.default

Источник – https://css-tricks.com/the-trick-to-viewport-units-on-mobile/

Как исправить проблему кроссбраузерности safari ios 9 overflow, 100vh?

Решил проблему так:

html {
height: 100%;
}

.m-openSideMenu {
min-height: 100%;
}
.m-openSideMenu .inner,
.m-openSideMenu .sidebar,
.m-openSideMenu .sticky {
height: 100%;
}

Позже выложу пример

Как пофиксить 100vh в safari ios?

Ребят, как пофиксить 100vh в safari а iphone? Мне нужно верхнюю секцию на странице растянуть на всю высоту видимой области браузера.
Нашел только одно решение более менее подходящее:
let vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);

min-height: calc(var(--vh, 1vh) * 100);

Оно вроде как работает, но если перейти с обычной страницы на ту, в которой главная секция должна быть на весь экран, то не правильно высчитывается высота и все улетает в низ. Если обновить эту страницу, то все пересчитается и встанет как надо.

Оцените статью
iPad Мобайл