Home > other >  CSS huge image as whole site background with responsiveness
CSS huge image as whole site background with responsiveness

Time:12-30

I have 11_100px(height) x 3_840px(width) image that I want to fit on my website, I managed to somehow fit it for desktop size using the padding-top trick calc(height / width * 100%) to calculate aspect ratio). But when resizing viewport it becomes impossible to maintain for tablet and mobile.

Somehow I need to make the height fully reliable to the width size

I wasn't able to find any stack overflow sufficient answer, how are such large backgrounds handled for all devices?

Example: link to my example

CodePudding user response:

The best way to achieve this is by adding a background image to a div.

body {
  margin: 0;
}

div {
  width: 100vw;
  height: 100vh;
  background-image: url("https://via.placeholder.com/500x500.png?text=Placeholder");
  background-size: cover;
  background-position: center;
}
<div></div>

CodePudding user response:

You can define a background-image for bodyto which you apply the below settings (except using your own image of course).

The background image will not scroll with the content in this case - I suppose this is what you want.

body {
  margin: 0;
  background-image: url("https://picsum.photos/1200/1600");
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

CodePudding user response:

You can also do this to scale the image to fit the width of the screen and if the width is too long it will be hidden.

body {
  background: url("https://picsum.photos/1200/1600");
  background-size: cover;
  object-fit: cover;
  width: 100vw;
  z-index: -1;
  overflow-x: hidden;
}

nav {
  height: 10vh;
  width: 100vw;
}

footer {
  height: 10vh;
  width: 100vw;
}
<html>

<head>
</head>

<body>
</body>

</html>

  • Related