As I noted above, we need to find the formula, so the idea is to rely on the logic background-position:center and background-size:cover . Since the image will always be stretched, we have two options:
- The top of the image will be the same as the top of the div, and thus top = 0
- The height of the image will be greater than the div, and the top will be hidden and thus top <0

As you can see, I was considering the top position relative to the top of the div, which is the source for me
Now we need to consider all the different cases of how an image covers a div and calculates a new image height depending on each situation.
Here is a sample code:
body { height: 100vh; } .parallax3 { position: relative; background-position: center center; background-repeat: no-repeat; background-size: cover; background-image:url('https://picsum.photos/g/200/600'); height: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="parallax3"> </div>
If we consider containing as a value in the background size, the image will always be contained inside a div, so there are two possibilities:
- The top of the image will be the same as the top of the div, and thus top = 0
- The image will be smaller in height, and the upper part of the image will be visible and, thus, the top> 0

The same as above, we need to consider different situations and calculate a new image height.
Here is a sample code:
body { height: 100vh; } .parallax3 { position: relative; background-position: center center; background-repeat: no-repeat; background-size: contain; background-image: url('https://picsum.photos/g/200/600'); height: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="parallax3"> </div>
Both fragments can be optimized to reduce redundancy, but I saved them to better explain different situations.
source share