CSS background-image displaying incorrectly

49 views Asked by At

I'm trying to display a background image on a webpage, and it's showing the bottom two thirds of the image, followed by the top one third.

It's not a problem with the .jpg file; I tried a completely different image, identical symptoms.

I've boiled it down to a minimum test case, that just shows the image and nothing else. Browser is the latest version of Chrome on Windows 11.

If I replace cover with contain or 100% 100%, the image disappears completely.

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      background-image: url('https://picsum.photos/1920/1080');
      background-size: cover;
      background-position: center;
    }
  </style>
</head>

<body>
</body>

</html>

2

There are 2 answers

3
Chinz On BEST ANSWER

The reason for this is that your html does not have any defined height yet.

Add a height to the body and html, this will do the job.

html,
body {
  height: 100%;
}
0
Dato On

If you want to display background image with full height, full width and without repeat itself try to add this into body styles:

  height: 100vh;
  width: 100vw;
  background-repeat: no-repeat;