category: prog, direction: js, group: django
Проблема vh в мобильных
Ключи: #css, #js
Добавлено: 13-02-2025. Обновлено: 15-02-2025
Решение: JS + CSS = vh
В мобильном, единицы размеров vh, vw
не учитывают элементы браузера и используют всю высоту экрана.
Что бы элементы браузера не сдвигали содержимое страницы,
при указании высоты содержимого в 100vh
можно рассчитывать эту единицу через js
и добавлять в виде переменной, для участия в расчётах css.
JS:
// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);
// We listen to the resize event
window.addEventListener('resize', () => {
// We execute the same script as before
let vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
});
CSS:
.my-element {
height: 100vh; /* Fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
Источник решения: The trick to viewport units on mobile