Bag*_*kri 9 html css reactjs styled-components
我想在手机上裁剪我的背景,这样用户就无法水平滚动,当我在网络浏览器上使用响应式设计模式时,它工作得很好:
但是当我在手机上打开它时,它显示如下:
我知道这个问题已经被问过很多次了,但似乎没有一个解决方案对我有用。
这是我的代码:
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;
}
`Run Code Online (Sandbox Code Playgroud)
这是我网站的链接,以防需要:https ://trusting-bohr-a3f5b8.netlify.app/
我的猜测是您在 iPhone 上使用 Safari 浏览器,并且根据Can I Use 的说法,clip不幸的是 Safari 不支持 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;
}
`
Run Code Online (Sandbox Code Playgroud)
这项工作有三个关键:
max-width: 100vw意味着 div 永远不会比屏幕长。overflow: hidden意味着图像不会从其约束 div 中泄漏出来。
hiddenonWrapper会隐藏整个图像,因为它最终的高度为 0。这就是引入额外 div 的原因。我还建议调查是否有办法将您的图像用作background-image.