8

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;
} 
Brad Adams
  • 2,066
  • 4
  • 29
  • 38
  • 1
    `background-attachment` does not strictly apply to images...but rather elements with `background-images` [**MDN Link**](https://developer.mozilla.org/en/docs/Web/CSS/background-attachment)...so it's not really clear wha you are asking. – Paulie_D Nov 05 '15 at 17:01
  • Is there a workaround this? What could you do to achieve the same affect on an `` without using `background-image`? –  Nov 05 '15 at 17:05
  • It's not clear what you are trying to do...perhaps you could [edit] your question with more information and meaningful code. – Paulie_D Nov 05 '15 at 17:06
  • @Ozzy Check my answer, but I'm not sure that I understood your question correctly, because bit unclear. – CroaToa Nov 05 '15 at 17:10

4 Answers4

18

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>
Cato
  • 439
  • 3
  • 7
2

You cant do that. First of all background-attachment is CSS "function", and you can give that ONLY for background-image. You can also get similar view, with position:fixed to img.

img {
     position: fixed;
} 

Try JsFiddle

CroaToa
  • 900
  • 2
  • 14
  • 36
1

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; }
Lawrence Johnson
  • 3,924
  • 2
  • 17
  • 30
1

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.

Todd Nestor
  • 136
  • 4