TIL: Making a Background Fill The Page

We ran into a bug at work today when doing some retests. Rather than wait on development to fix the issue, I decided to play around with the code myself and see if I could fix the issue myself.

The problem that we ran into was that the background image on the website was being tiled, rather than filling the screen. This tiling was present when the screen was too small (repeating on x), and if the screen was too narrow (repeat y).

My fix

When I checked the styling, I found that they were setting the background-size equal to 100%. While this fixed things when the screen was larger, it broke as soon as the screen was narrowed. This was true for mobile sized browsing as well.

Now I know that this could have been solved by adding media queries based on screen sizes, but I wanted to find another solution to the problem.

My solution was to change the background-size from 100% to using viewport units. Max them out to fill the screen:

1
background-size: 100vw 100vh;

This was better, but now the background image got all distorted when shrunk. I didn’t want it to look that ugly.

The next thought was to try using cover. After changing to this, I found that the page was filling width wise, but still not vertically. So that didn’t solve the issue.

The final fix

Development came back with their fix and it was actually just one extra step on top of using the cover parameter. That was to add a min-height parameter and set it equal to 100%:

1
min-height: 100%

This then forced the image to always fill the screen vertically, kept the image in the same position when making it smaller, and then stretching larger when it moved passed it’s actual size.

💚