为什么在移动浏览器上使用overflow-x: clip无效?

8

我想在手机上裁剪背景,以便用户无法水平滚动,在Web浏览器的响应式设计模式下使用时效果很好:

enter image description here

但是当我在我的手机上打开它时,它显示如下:

enter image description here

我是一位有用的助手,可以为您进行文本翻译。以下是需要翻译的内容:

我知道这个问题已经被问了很多次,但是没有一个解决方案对我有效。

这是我的代码:

import React from "react"
import styled from "styled-components"

const HeroBackground = () => {
  return (
    <Wrapper>
      <Background src="/images/backgrounds/hero-background.svg" />
    </Wrapper>
  )
}

export default HeroBackground

const Wrapper = styled.div`
  position: relative;
  max-width: 1440px;
  margin: auto;
  overflow-x: clip !important;
`

const Background = styled.img`
  position: absolute;
  z-index: -1;
  @media (max-width: 480px) {
    max-width: 600px;
    height: auto;
  }
`

如果需要,这是我的网站链接: https://trusting-bohr-a3f5b8.netlify.app/

2个回答

4

我猜你在iPhone上使用的是Safari浏览器,根据Can I Use的数据,clip在Safari中不受支持,这就导致了你看到的差异。

我尝试进行调整以实现你想要的效果。一种可能的解决方案是在img周围再加一个包装

const HeroBackground = () => {
  return (
    <Wrapper>
      <ImageWrapper>
        <Background src="/images/backgrounds/hero-background.svg" />
      </ImageWrapper>
    </Wrapper>
  )
}

export default HeroBackground

const Wrapper = styled.div`
  position: relative;
  max-width: 1440px;
  margin: auto;
  /* overflow-x: clip !important; ***cannot use!*** */
`

const ImageWrapper = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  max-width: 100vw;
  z-index: -1;
`

const Background = styled.img`
  /* position: absolute; ***remove*** */
  /* z-index: -1; ***remove*** */
  @media (max-width: 480px) {
    max-width: 600px;
    height: auto;
  }
`

这需要三个要点才能实现:
  • 添加额外的包装 div 让图片以静态定位的方式进行布局,使其为高度做出贡献。因此,div 成为绝对定位的元素。
  • max-width: 100vw 表示该 div 不会超出屏幕的长度。
  • overflow: hidden 意味着图片不会溢出其约束的 div
    • Wrapper 上使用 hidden 会隐藏整个图片,因为它最终的高度为零。这就是为什么要引入额外的 div 的原因。
我还建议探索一下是否有一种方法可以将您的图片用作 background-image

是的,解决方案有效! 很奇怪,因为我在许多设备上测试过,包括安卓手机,但overflow-x剪辑似乎也不起作用。 感谢您的解决方案,尽管我仍然对额外的div有点困惑。 - Bagus Amrullah Fikri
仍然完美运作。@BagusAmrullahFikri 额外的div是为了可以关闭父级(当前包含图像的div)的overflow:clip,而绝对定位的div则让您可以将内容移动到父级之外。Overflow仍然有效,但现在可以在直接图像包装器上隐藏它,同时允许父级上的可见溢出。 - Andrew West

3
我在IOS / Safari上遇到了同样的问题,但我刚刚注意到Can I Use现在显示overflow:clip将在IOS 16.0的Safari中得到支持。这是从现在开始考虑的事情,在实施解决方法之前,请考虑你有多少用户将来会使用旧版本的IOS以及 overflow: clip 无法正常工作的影响有多大。在我的情况下,影响仅限于一些内容突出比旧版IOS上预期的更多,这是我可以接受的。

2
使用overflow-x: hidden代替overflow-x: clip对你来说是一个选项吗?这就是我为自己解决问题的方法。在较大的屏幕上,我需要overflow-x: clip,但对于移动设备,overflow: hidden就足够了,所以只需将其放入媒体查询中即可。 - Luke
在某些情况下,这确实可能也有效!在我这种情况下,没有使用“hidden”的原因是有原因的,尽管如果只在移动设备上使用“hidden”并在较大的屏幕上剪辑,就可以解决问题。然而,在我的情况下,网站中有一些区域需要特别在移动设备上进行裁剪,因为我将其与overflow-clip-margin结合使用,这也是一个非常有用的属性。 - GoldyOnline

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接