Steve Waters
Steve Waters

Reputation: 3548

Background image without specific height

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?

Upvotes: 0

Views: 333

Answers (2)

Zuber
Zuber

Reputation: 3473

try VH instead of px for height. hope it will work

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

`;

Upvotes: 1

Athul Nath
Athul Nath

Reputation: 2606

Give viewport height

height:100vh;

Upvotes: 2

Related Questions