cristinafsanz
6/21/2019 - 3:50 PM

Viewport units on mobile

Note: In less would be height: ~"calc(var(--vh, 1vh) * 100)";

Other articles about this:

# Source: https://css-tricks.com/the-trick-to-viewport-units-on-mobile/

// First we get the viewport height and we multiple it by 1% to get a value for a vh unit)
const 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`)
/* To correct display height for mobile */
/* https://css-tricks.com/the-trick-to-viewport-units-on-mobile/ */
.header-background {
  height: 100vh;
  height: calc(var(--vh, 1vh) * 100);
  
  /* For mobile and landscape not use 100vh */
  @media screen and (orientation:landscape) {
    height: auto;
  }
  
  @media (min-width: $min-width-tablet) {
    height: auto;
  }
}


<script>
export default {
  data() {
    return {
      scrolled: false
    }
  },
  mounted: function () {
    // To correct display height for mobile
    if (process.browser) {
      window.addEventListener('scroll', this.handleScroll)
      this.displayCorrectHeightForMobile()
      window.addEventListener('resize', () => {
        this.displayCorrectHeightForMobile()
      })
    }
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll() {
      this.scrolled = window.scrollY > 0
      const headerBackground = document.querySelector('.header-background')
      const offsetHeight = headerBackground.offsetHeight
      if (this.scrolled) {
        headerBackground.style.height = offsetHeight + 'px'
      }
    },
    displayCorrectHeightForMobile() {
      if (!this.scrolled) {
        // First we get the viewport height and we multiple it by 1% to get a value for a vh unit)
        const 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`)
      }
    }
  }
}
</script>
import { ready } from './utils';

let scrolled = false;

function handleScroll() {
  scrolled = window.scrollY > 0;
  const headerBackground = document.querySelector('#menu-toggle:checked ~ .menu');
  const { offsetHeight } = headerBackground;
  if (scrolled) {
    headerBackground.style.height = `${offsetHeight}px`;
  }
}

function displayCorrectHeightForMobile() {
  // First we get the viewport height and we multiple it by 1% to get a value for a vh unit)
  const 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`);
}

ready().then(() => {
  window.addEventListener('scroll', handleScroll);
  displayCorrectHeightForMobile();

  window.addEventListener('resize', () => {
    displayCorrectHeightForMobile();
  });
});