Ad

Background Image Without Specific Height

- 1 answer

I'm creating a React page.

I want to add a background image that covers the background no matter the window size or resolution etc.

so here's what I have for the background.

import coolImportedImage from '../../images/image_background.jpg';

const BackGroundContainer = styled.div`
    background-image: url(${coolImportedImage});
    background-repeat: no-repeat;
    background-size:cover;
    width: 100%;
    height: 1080px;
`;

...and the render method:

render(){

    return(
      <BackGroundContainer>
        <CenteredLoginPanel>
          ...some components...
        </CenteredLoginPanel>
      </BackGroundContainer>
    );
  }

It's working except I'd like the height also to be relative. Just filling the background of the window as the width does.

However, height doesn't work with 100%. It needs to have a specific value such as 1080px (this image is 1080px high).

Now, I know the reason for this. a div has to have some content to render. But what I'm looking for is the best practice for getting what I want to do here, which is a background covering the width and the height of the window.

Or is there a better way to do this altogether as in is my approach with the div wrong to begin with?

Ad

Answer

Give viewport height

height:100vh;
Ad
source: stackoverflow.com
Ad