25

I'm trying to set a background image in React but it only covers about 75% of the height.

It seems that the component doesn't take up all of the height.

What's the solution?

In index.js:

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

In index.css:

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

In Login.js:

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

In Login.css

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

The end result: Screen shot

Andre Hofmeister
  • 2,865
  • 11
  • 47
  • 72

5 Answers5

32

Use vh and vw properties:

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

Try using the specific property values.

In Index.css:

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

In 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;
}
otolock
  • 612
  • 4
  • 23
17

The image should be inside your src folder besides that, inside your component you do the following.-

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>
    );
  }
}
Jorge Carretero
  • 361
  • 2
  • 12
0

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.

tay_thomp
  • 245
  • 2
  • 12
0

Edit the 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

5ar
  • 1,920
  • 12
  • 22