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

Material UI中如何创建带顶部标题的Box或Paper组件?

实现带左上角悬浮标题的Box/Paper组件

Material-UI的Box和Paper组件本身没有内置带左上角标题的配置,但可以通过定位+样式调整轻松实现你想要的效果,核心思路是让标题绝对定位在容器左上角,通过背景色覆盖容器边框,营造出嵌入的视觉效果。

示例代码(MUI v5,使用sx属性)

import { Paper, Typography, Box } from '@mui/material';

const HeaderContainer = () => {
  return (
    <Paper 
      sx={{
        position: 'relative',
        padding: '2rem 1rem 1rem', // 顶部留空避免内容被标题遮挡
        border: '1px solid #e0e0e0',
        maxWidth: 400,
        margin: '2rem auto',
        backgroundColor: '#fff'
      }}
    >
      {/* 左上角标题 */}
      <Typography
        sx={{
          position: 'absolute',
          top: '-0.75rem', // 向上偏移,覆盖边框
          left: '1rem',
          backgroundColor: '#fff', // 和容器背景一致,盖住边框
          padding: '0 0.5rem',
          fontWeight: 600,
          fontSize: '0.9rem'
        }}
      >
        自定义标题
      </Typography>
      
      {/* 容器内容 */}
      <Box>
        这里是容器内的内容区域,可放置任意组件或文本。
        <br />
        测试内容,确保不会被标题遮挡。
      </Box>
    </Paper>
  );
};

export default HeaderContainer;

关键样式说明

  • 容器(Paper/Box)需设置position: relative,让标题的绝对定位以容器为基准
  • 标题设置position: absolute,通过top值向上偏移,配合背景色覆盖容器边框
  • 容器的padding-top要足够大,避免内容与标题重叠
  • 如果用Box代替Paper,只需替换组件并调整Box的边框、阴影样式即可,逻辑完全一致

MUI v4 兼容写法(使用makeStyles)

import { makeStyles } from '@material-ui/core/styles';
import { Paper, Typography, Box } from '@material-ui/core';

const useStyles = makeStyles(theme => ({
  container: {
    position: 'relative',
    padding: theme.spacing(4, 2, 2),
    border: '1px solid #e0e0e0',
    maxWidth: 400,
    margin: theme.spacing(2, 'auto'),
    backgroundColor: theme.palette.background.paper
  },
  headerTitle: {
    position: 'absolute',
    top: theme.spacing(-1),
    left: theme.spacing(2),
    backgroundColor: theme.palette.background.paper,
    padding: theme.spacing(0, 1),
    fontWeight: 600,
    fontSize: '0.9rem'
  }
}));

const HeaderContainer = () => {
  const classes = useStyles();
  
  return (
    <Paper className={classes.container}>
      <Typography className={classes.headerTitle}>自定义标题</Typography>
      <Box>
        这里是容器内的内容区域,可放置任意组件或文本。
        <br />
        测试内容,确保不会被标题遮挡。
      </Box>
    </Paper>
  );
};

export default HeaderContainer;

内容的提问来源于stack exchange,提问作者Jean-François Handfield

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:01:20