Background image without specific height

你离开我真会死。 提交于 2019-12-11 15:37:33

问题


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?


回答1:


Give viewport height

height:100vh;



回答2:


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;

`;



来源:https://stackoverflow.com/questions/48803301/background-image-without-specific-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!