CSS solution for background image to cover full page with overflow elements

  css, javascript, reactjs, sass

I’ve got a page that uses an image as a background, which covers the full height and width of the page. Although I’m using Tailwind, the CSS for the image is basically:

  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  position: absolute;
  top: 0;
  width: 100%;

That works fine. Until one of the elements on the page extends beyond my viewheight, which usually occurs when a toggle is switched on. CSS doesn’t seem to recognize that the height of the page has no changed, so it doesn’t update the size of the image. It simply ends at the point where the bottom of the page used to be, before the extending element lengthened the page.

I’ve created a javascript solution for this that does some calculations based on the size of elements and directly sets the height of the image with inline styling, but it’s not ideal, so I’ve been tasked with finding a pure CSS solution. I’m aware that updating the image height without adjusting the dimensions of the image will cause stretching, but in that case that’s not a problem.

Obviously different from my webpage, but here’s a codesandbox demonstrating essentially the same problem.

Source: Ask Javascript Questions