Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i have portrait image (width: 869px; height: 2853px) which i wanna use as the background image for my website. the image should be responsive and always fill the entire width of the browser window. the image should keep its proportions and should never be cropped. therefor the height needs to adjust to the given width. since the image height is always bigger than the viewport height, you should be able to scroll to the bottom of the image, which should be the bottom of the website as well.

i'd really appreciate if someone would tell me how to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
297 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think the other commenters are ignoring your request for help in not "cropping" the image, when they keep suggesting use of background-size: cover.

Here's what I've gathered are your requirements:

  • An image to be a background, behind the content of your site.
  • The background image has a specific aspect ratio and should not be cropped
  • If the browser window doesn't match the images aspect ratio, it should allow scrolling vertically, but should always fit to the windows width.

A css only solution...

body {
  position: relative;
  margin: 0;
}
body::before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: -1;
  height: 0;
  /* height / width = ratio% */
  /* 2853px / 869px = 328.3084% */
  padding-bottom: 328.3084%;
  padding-bottom: calc(2853 / 869 * 100%);
  background: url('//placekitten.com/869/2853') center top / 100% auto no-repeat;
}

Replace the url with the url of your image, and if the image pixel dimensions change, update those in the way I have commented out how padding-bottom should be calculated.

This creates a separate background element inside the body of the website and still allows you to have whatever content you want inside your site. But keep in mind, if you're on a very small screen, say 320px/480px, and the websites content becomes very tall because of the narrow width of the screen, this background image could be scrolled passed to account for the content. That won't break this code, but I would just suggest adding a background color or texture to your html element, which would show below the image in this case. Good luck.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...