简体   繁体   中英

Background image with react js - not displaying full screen

I'm used to react native and trying my hand at reactjs, however I'm getting really frustrated with myself as I understand a lot of how react works from using react native but I can't style my components properly as I'm not used to css.

I'm using the ant design UI framework to help me build a small web application, and as of now I have my nav bar along the top of the app but want to set an image below that takes up 100% of the screen and have the height auto set to the aspect ratio.

I'm currently trying this but it doesn't work.

<div className="background">
</div>

//In App.css

.background {
  background-image: url('./assets/main-image.jpg');
  background-size: 'contain';
  width: 100%;
  height: auto;
}

I've tried the above but and a few other methods but nothing is working. It appears that the height is dependent upon whatever the content inside the div is. For example, if I place a h1 tag inside the div then I can see the image but only a few pixels in height.

My image is 4000px in width and is landscape. I just want to be able to dynamically display the image depending on screen resolution.

Can someone point me in the right direction?

Thanks

Edit: I've now set my css background class to this and it's nearly there.

  background-image: url('./assets/main-image.jpg');
  background-size: contain;
  background-repeat: no-repeat;
  width: 100%;
  height: 100vh;

The only issue is now I'm left with a decent size of padding below the image due to it rendering the full height of my view port

Try this:

position: fixed;
top: 0;
width: 100%;
height: 100%;
background-size: cover;
background-image: url('background.jpg');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM