How would you use the CSS style background-attachment
and apply it to an <img>
tag?
<img src="ok.jpg">
CSS:
img {
background-attachment: fixed;
}
How would you use the CSS style background-attachment
and apply it to an <img>
tag?
<img src="ok.jpg">
CSS:
img {
background-attachment: fixed;
}
Adding this in case anyone else gets here looking to replicate the behavior of background-attachment: fixed;
while using an img
tag in HTML.
You cannot use background properties on an <img>
tag as requested, but you CAN replicate it's behavior by using position: fixed
on the image and clip-path
on it's container.
Example:
div {
position: relative;
height: 200px;
margin: 50px 10px;
clip-path: inset(0);
}
img {
object-fit: cover;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
body {
min-height: 400px;
}
<div>
<img src="https://picsum.photos/id/237/200/300">
</div>
Well, background-attachment is not going to work the image src. You'd have to have something like this:
<div class="img"></div>
CSS
.img { background-image: url('ok.jpg'); background-attachment: fixed; }
You don't generally use background-attachment for an <img>
tag.
What you actually want to do is set your image as a background for something like the body or a div and then set the attachment to fixed.
<style>
.bg-image {
background-image: url(ok.jpg);
background-attachment:fixed;
}
</style>
<div class='bg-image'></div>
Or something along those lines.
You'll probably want to set the height
or min-height
for the div also so that you can ensure it shows up.
Also you might want to play with the background-repeat styles, by default it will repeat both on x and y.