【问题标题】:Why is overflow-x:clip not working on mobile browser为什么overflow-x:clip 在移动浏览器上不起作用
【发布时间】:2021-08-16 13:25:18
【问题描述】:

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

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

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

这是我的代码:

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


    【解决方案1】:

    我的猜测是您在 iphone 上使用 Safari 浏览器,根据Can I Use,很遗憾 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 中泄漏出来。
      • Wrapper 上使用hidden 会隐藏整个图像,因为它的高度为0。这就是引入额外 div 的原因。

    我还建议调查是否有办法将您的图片用作background-image

    【讨论】:

    • 是的,解决方案有效!这很奇怪,因为我在包括 android 手机在内的许多设备上对其进行了测试,但 overflow-x 剪辑似乎也不起作用。感谢您的解决方案,尽管我仍然对额外的 div 有点困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多