You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React基于屏幕分辨率动态定位组件实现餐厅落地页适配问题

解决方案

核心思路

放弃手动计算left值做定位的方式,改用相对+绝对定位结合MUI Grid原生布局能力实现自适应相对位置,无需额外计算坐标。

具体修改点

  • 社交图标固定右上角
    1. 给最外层承载背景图的Grid容器添加position: 'relative'属性,作为所有绝对定位元素的父级参照
    2. 删掉SocialIcon上的left: width / 4属性
    3. 包裹社交图标的ButtonGroup外层Grid容器修改为绝对定位,设置top: 4vh、right: 4vw,即可固定在右上角相对位置,任意尺寸下位置比例保持一致
  • Paper组件左侧定位+间距设置
    1. 包裹Paper的Grid容器设置绝对定位,添加left: 8vw、top: 50%、transform: 'translateY(-50%)'属性,实现左侧垂直居中的相对定位
    2. 把原来包裹三个CustomPaper的Typography组件替换为<Grid container direction="vertical" gap={2.5} sx={{display: 'inline-grid'}}>,即可同时实现垂直排列、组件间距、inline-grid属性的要求
  • 优化项
    1. 给CustomPaper添加minWidth: 120px、minHeight: 40px属性,避免屏幕过小时组件被压缩到无法展示文字
    2. 将ThemeProvider移到LandingPage组件外层,避免窗口resize时重复创建主题实例

核心代码修改示例

return (
  <Grid
    container
    xs={12}
    sx={{
      position: 'relative', // 新增父级相对定位
      backgroundImage: `url(${backgroundImage})`,
      backgroundPosition: "top",
      backgroundSize: "cover",
      backgroundRepeat: "no-repeat",
      height: "100vh",
      width: "100vw",
      overflow: "auto"
    }}
  >
    {/* 社交图标区域 */}
    <Grid sx={{ position: 'absolute', top: '4vh', right: '4vw' }}>
      <ButtonGroup orientation="vertical" sx={{ gap: 1 }}>
        <SocialIcon
          style={{ height: height / 12, width: height / 12 }}
          url="https://www.tiktok.com/@bennysburger"
          target="_blank"
          rel="noopener noreferrer"
          bgColor="white"
        />
        {/* 其余两个SocialIcon同上删掉left属性即可 */}
      </ButtonGroup>
    </Grid>
    {/* Paper菜单区域 */}
    <Grid 
      container 
      sx={{ 
        position: 'absolute', 
        left: '8vw', 
        top: '50%', 
        transform: 'translateY(-50%)' 
      }}
    >
      <ThemeProvider theme={theme}>
        <Grid container direction="vertical" gap={2.5} sx={{display: 'inline-grid'}}>
          <Grid item>
            <CustomPaper>Orders</CustomPaper>
          </Grid>
          <Grid item>
            <CustomPaper>Menu</CustomPaper>
          </Grid>
          <Grid item>
            <CustomPaper>Gallery</CustomPaper>
          </Grid>
        </Grid>
      </ThemeProvider>
    </Grid>
  </Grid>
);

内容的提问来源于stack exchange,提问作者Kahalon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:45:03