1

I'm trying to create a website, where the background image is going to be centered, and and it will resize itself based on the web browser window, but only till reaching its original size. After that it will stop becoming larger and just stay centered. Is there a way to do this using CSS? I have drawn some examples to better explain myself. Here, width of the site is larger than the width of the actual image, so the image reaches its maximal width and stays there. However, the height of the image shown is either higher or equal to the height of the window, so it comes from top to bottom. Also if the width of the site is larger than the width of the picture, but height isn't, I don't want to see just a part of that picture, I would love it to automatically resize so it fits the screen - something like zooming. And here is shown that if the height and width of the site are greater than the width and height of the actual picture, it just stays centered. I've got some code, but I cannot get it working since I'm pretty new to CSS. Code:

body{
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Am I right in understanding that you don't want background-size cover but you want the image size to go all the way on width and/or height of the window if and only if its natural dimensions are at least as large as those. Otherwise you want it to keep its natural width and height - ie so there is no loss of definition? – A Haworth Dec 19 '21 at 17:38

3 Answers3

0

You are able to use max-width and max-height to make it so it does not become larger than what you chose.

Ethan
  • 881
  • 8
  • 14
  • 26
0

just like I did in my Windows 11 Clone website :) https://codepen.io/laaouatni/pen/ZEXOpXw

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>

<style>
body {
    height: 100vh;
    width: 100vw;
    background-image: url(https://laaouatni.github.io/w11-clone/images/1dark.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-attachment: fixed;
    background-size: cover;
}
</style>
</html>

Laaouatni Anas
  • 4,199
  • 2
  • 7
  • 26
0

If you do not specify any dimensions for the image then it will be shown at its natural dimensions.

However, you can tell the system not to allow either the width or the height to go beyond the window sizes.

Here is a snippet demonstrating this with 3 images, one very wide and one small and one very tall:

body {
  width: 100vw;
  height: 100vh;
}

img {
  max-width: 100vw;
  max-height: 100vh;
}
<img src="https://picsum.photos/id/1015/2000/300" />
<img src="https://picsum.photos/id/1015/200/200" />
<img src="https://picsum.photos/id/1015/300/2000" />
A Haworth
  • 30,908
  • 4
  • 11
  • 14