在 Reactjs 中将背景图像设置为全屏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48288176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set background image to full screen in Reactjs
提问by
I'm trying to set a background image in React but it only covers about 75% of the height.
我正在尝试在 React 中设置背景图像,但它只覆盖了大约 75% 的高度。
It seems that the component doesn't take up all of the height.
似乎该组件并没有占据所有的高度。
What's the solution?
解决办法是什么?
In index.js:
在 index.js 中:
ReactDOM.render(<Login />, document.getElementById('root'));
In index.css:
在 index.css 中:
html, body, .Login-component {
height: 100%;
}
In Login.js:
在 Login.js 中:
render() {
return (
<div className='Login-component'>
);
}
In Login.css
在 Login.css 中
.Login-component {
background: url(../static/login-bg.jpg) no-repeat center center fixed;
background-size: cover;
}
The end result: Screen shot
最终结果:屏幕截图
采纳答案by otolock
Try using the specific property values.
尝试使用特定的属性值。
In Index.css:
在 Index.css 中:
body, html {
height: 100%;
margin: 0;
}
In Login.css:
在 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;
}
回答by Jorge Carretero
The image should be inside your src folder besides that, inside your component you do the following.-
图像应该在您的 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>
);
}
}
回答by Nick Sherman
Use vh and vw properties:
使用 vh 和 vw 属性:
const styles = {
container: {
backgroundImage: `url(${backgroundImage})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
width: '100vw',
height: '100vh'
}
};
回答by tay_thomp
While it is hard to troubleshoot without any code, check the root element to which your react component is being rendered to. Setting height: '100%'in the style of your component will be in the context of it's parent div.
虽然在没有任何代码的情况下很难进行故障排除,但请检查您的 React 组件要渲染到的根元素。height: '100%'组件样式中的设置将在其父 div 的上下文中。
回答by 5ar
Edit the CSS.
编辑 CSS。
This might be what you are looking for:
这可能是您正在寻找的:
<Component style={{ minHeight: '100%' }} />
If you meant that the background image is not covering the whole height, then add a className to your component, import the CSS where you'll do something like this
如果你的意思是,背景图像不覆盖整个高度,然后一个类名添加到您的组件,导入CSS在那里你会做这样的事情这

