为什么overflow-x:clip在移动浏览器上不起作用

问题描述 投票:0回答:3

我想在手机上裁剪我的背景,这样用户就无法水平滚动,当我在网络浏览器上使用响应式设计模式时,效果很好:

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

我知道这个问题已被问过很多次,但似乎没有一个解决方案适合我。

这是我的代码:

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/

html css reactjs styled-components
3个回答
5
投票

我的猜测是您在 iPhone 上使用 Safari 浏览器,并且根据 我可以使用,不幸的是 Safari 不支持

clip
,因此您看到了差异。

我尝试了一下,看看能否达到你想要的效果。一种可能的解决方案是在

img
周围再引入一个包裹 div。

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 中泄漏。
    • hidden
      上使用
      Wrapper
      会隐藏整个图像,因为它最终的高度为 0。这就是引入额外 div 的原因。

我还建议调查是否有办法将您的图像用作

background-image


3
投票

我在 IOS / Safari 上遇到了同样的问题,但我刚刚注意到 我可以使用 现在显示

overflow: clip
将在 IOS 16.0 中的 Safari 上受支持:)

从现在开始,在实施解决方法以使其在 IOS 上运行之前,需要考虑这一点。这一切都取决于未来有多少用户使用较旧的 IOS 版本,以及

overflow: clip
不工作的影响有多大。就我而言,影响仅限于某些突出显示的内容比旧版 iOS 版本上的预期更加突出,这是我可以忍受的。


0
投票

我将这个 CSS 类用于

overflow-x: clip
:

.polyfill-overflow-x-clip {
  /* On Safari mobile browsers, overflow-x-clip is not supported */
  overflow-x: hidden;
  overflow-x: clip;
}

© www.soinside.com 2019 - 2024. All rights reserved.