【问题标题】:Set background image to full screen in Reactjs在 Reactjs 中将背景图像设置为全屏
【发布时间】:2018-06-25 13:41:45
【问题描述】:

我正在尝试在 React 中设置背景图片,但它只覆盖了大约 75% 的高度。

似乎组件没有占据所有高度。

解决办法是什么?

在 index.js 中:

ReactDOM.render(<Login />, document.getElementById('root'));

在 index.css 中:

html, body, .Login-component {
  height: 100%;
}

在 Login.js 中:

render() {
    return (
      <div className='Login-component'>
    );
}

在 Login.css 中

.Login-component {
    background: url(../static/login-bg.jpg) no-repeat center center fixed;
  background-size: cover;
}

最终结果:Screen shot

【问题讨论】:

  • 你能显示一些代码吗?
  • 没有显示你尝试过的问题太宽泛了,这个问题有很多解决方案。
  • 编辑:添加代码:)

标签: reactjs


【解决方案1】:

虽然没有任何代码很难排除故障,但请检查你的 react 组件被渲染到的根元素。在组件的样式中设置height: '100%' 将在其父 div 的上下文中。

【讨论】:

    【解决方案2】:

    编辑 CSS。

    这可能是您正在寻找的:

    <Component style={{ minHeight: '100%' }} /> 
    

    如果你的意思是背景图片没有覆盖整个高度,那么在你的组件中添加一个 className,导入 CSS,你将在其中执行类似 this 的操作

    【讨论】:

      【解决方案3】:

      尝试使用特定的属性值。

      在 Index.css 中:

      body, html {
          height: 100%;
          margin: 0;
      }
      

      在 Login.css 中:

      .Login-component {
          /* The image used */
          background-image: url(../static/login-bg.jpg);
      
          /* Full height */
          height: 100%; 
      
          /* Center and scale the image nicely */
          background-position: center;
          background-repeat: no-repeat;
          background-size: cover;
      }
      

      【讨论】:

        【解决方案4】:

        除此之外,图像应该在您的 src 文件夹中,在您的组件中执行以下操作。-

        const imgMyimageexample = require('../assets/imageexample.jpg');
        const divStyle = {
          width: '88%',
          height: '800px',
          backgroundImage: `url(${imgMyimageexample})`,
          backgroundSize: 'cover'   <---- This is important
        };
        
        export default class Mycomponent extends React.Component {
          render() {
            return (
              <div className="cComponent" style={divStyle} >
                <h1 align="center">Some header example</h1>
              </div>
            );
          }
        }
        

        【讨论】:

        • 超过 800px 的屏幕就不行了,对吧?
        【解决方案5】:

        使用 vh 和 vw 属性:

        const styles = {
            container: {
                backgroundImage: `url(${backgroundImage})`,
                backgroundPosition: 'center',
                backgroundSize: 'cover',
                backgroundRepeat: 'no-repeat',
                width: '100vw',
                height: '100vh'
            }
        };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-13
          • 2020-10-27
          • 2016-12-31
          • 2014-05-18
          相关资源
          最近更新 更多