如何根据页面内容更改背景图像的高度

时间:2019-06-12 12:33:28

标签: css reactjs material-ui

根据页面内容的数量,我在获取背景图片以填充屏幕时遇到问题。我的应用程序由一个主div和一个侧栏导航组成。我将背景图片样式设置为主要div,如下所示:

const styles = makeStyles(theme => ({
  backgroundStyle: {
    flexGrow: 1,
    padding: theme.spacing(3),
    height: '100vh',
    textAlign: 'center',
    backgroundImage: `url(${Background})`,
    backgroundRepeat: "no-repeat",
    backgroundPosition: "center center",
    backgroundSize: "cover",
    backgroundAttachment: "fixed",
    [theme.breakpoints.down('md')]: {
      height: '100%'
    }
  }

height: '100vh'的效果很好,直到我选择了一个超出视图高度的导航项,该导航项会切断背景图像。将高度设置为height: '100%'可以解决此问题,但是对于内容不多的导航项目,背景图像不会占据整个屏幕。切换到响应视图时,我也遇到相同的问题。

我设置了条件来处理此问题:

return <main className={navListItem === 'Topic1' ? backgroundStyle : backgroundStyle2 }>

但是感觉就像我在重复自己,因为我正在创建另一个名为backgroundStyle2的类,该类包含所有相同的样式,只是高度设置为“ 100%”而不是“ 100vh”

我认为除了使用'100%'或'100vh'之外,还必须有一种更轻松的方法来根据页面内容更改背景图像,但我无法弄清楚

1 个答案:

答案 0 :(得分:1)

如果您希望具有至少100vh的高度,并且还希望根据内容的高度扩展该高度(如果内容的高度大于视口高度),则应使用minHeight:100vh; height:100%

const styles = makeStyles(theme => ({
  backgroundStyle: {
  flexGrow: 1,
  padding: theme.spacing(3),
  height: '100%',
  minHeight:'100vh',
  textAlign: 'center',
  backgroundImage: `url(${Background})`,
  backgroundRepeat: "no-repeat",
  backgroundPosition: "center center",
  backgroundSize: "cover",
  backgroundAttachment: "fixed",
  [theme.breakpoints.down('md')]: {
    height: '100%'
  }
}
相关问题