如何使用CSS在iOS上访问真实的100vh

如何使用CSS在iOS上访问真实的100vh

本文介绍了如何使用CSS在iOS上访问真实的100vh的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

这是自我问答集

如果您曾经尝试在iOS上的CSS中使用100vh,则会发现在扩展浏览器镶边时,它实际上不是100vh.苹果公司认为这是一个有据可查的错误,实际上是一项功能!这是很好的阅读说明错误.

那么解决这个功能"的最佳方法是什么?理想情况下,答案不需要JavaScript(但似乎不太可能),应该干净,不需要一堆内联样式,理想情况下可以在CSS中选择(有时您可能需要默认的100vh).

解决方案

像在样式表中那样设置根CSS变量:

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

然后在JavaScript中,在加载(或jQuery就绪)并调整大小时,您要运行以下代码:

     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)
    }
 

现在,您可以简单地使用CSS:height: var(--real100vh);,只要您想让100vh在移动设备上真正成为真正的100vh,这将很简单!

如果您还在同一元素上添加transition: height 0.4s ease-in-out;看起来会更好,因此在移动设备上向下滚动时它不会对齐.

使用CSS var进行此操作的优点是您可以在需要时覆盖它,例如,您可能希望某些断点为height: 500px,而如果使用内联样式则很难做到这一点.您也可以在calc()内部使用它,例如height: calc(var(real100vh) - 100px);,它对于固定标头很有用.

如果您使用Vue/Nuxt,请查看我们是如何在这里实现的.

This is a self Q&A

If you've ever tried to use 100vh in CSS on iOS you will have found that it isn't actually 100vh when the browser chrome is expanded. It's a well documented bug that Apple decided was actually a feature! This is a good read to explain the bug.

So what is the best way to get around this "feature"? Ideally the answer requires no JavaScript (but that seems unlikely), should be clean, not require a bunch of inline styles, and ideally can be opted into in CSS (sometimes you might want the default 100vh).

解决方案

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.

这篇关于如何使用CSS在iOS上访问真实的100vh的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:07