Home > Net >  How stretching an image fullscreen like a background-image with background-size: cover?
How stretching an image fullscreen like a background-image with background-size: cover?

Time:02-02

How to make a normal image (be it img or svg) behave exactly like a background-image ? I mean, covering the whole screen and getting cropped to never display borders ?

Only css, no javascript.

I tried this, mostly from img behaving like a background img?

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body, html {
    height: 100%;
    margin: 0;
}

.bg {
    background-image: url("./demo.jpg");
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    height: 100%; 
}
</style>

</head>

<body>
<div >
<img src="./demo.jpg" style="position:fixed; z-index:-5000; top: 50%; left: 50%; margin-left: -960px; margin-top: -540px" >

</div>

</body>

</html>

The "demo.jpg" image is 1920x1080.

It works somewhat, but the top picture doesn't get "squeezed" if the window gets too narrow.

And if I switch the image to a svg, it refuses to get "cropped", it is always "contain".

Any idea ?

CodePudding user response:

You are trying to have a responsive image on top of the background image? If so try width 100% height auto on the demo img maybe.

CodePudding user response:

use object-fit:cover

img {
  position:fixed;
  inset:0;
  width:100%;
  height:100%;
  object-fit:cover;
}
<img src="https://picsum.photos/id/1069/1000/1000">

  •  Tags:  
  • Related