Home > database >  How to make background image resize itself, but only till its original size reached?
How to make background image resize itself, but only till its original size reached?

Time:12-20

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;
}

CodePudding user response:

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

CodePudding user response:

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>

CodePudding user response:

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" />

  • Related