0

I wanna pick the src attribute value on the HTML and pass it to the css/scss file in a variable to be able to just add it to the url() property:

<style>
     img[src]{
        background-image:url(attr(src));
        }
</style>

And for every different img just grab their src value, add it inside the url property and make it the background image so I don't have to code a lot or code each single different image.

-

I've tried but does not work, i also tried using custom properties but i wanna confirm that there is no way to do this or a similar solution.

Thanks

  • 4
    he attr() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. ( from https://developer.mozilla.org/en-US/docs/Web/CSS/attr() ) – Gert B. Sep 29 '21 at 12:16
  • Duplicate of * https://stackoverflow.com/questions/26967890/css-set-background-image-by-data-image-attr – Jaredcheeda Sep 30 '21 at 12:08
  • Does this answer your question? [CSS set background-image by data-image attr](https://stackoverflow.com/questions/26967890/css-set-background-image-by-data-image-attr) – Jaredcheeda Sep 30 '21 at 12:09

1 Answers1

0

No, you will need javascript to get the value attribute and use it as a value elsewhere

here a possible example with a css var(--var) so it can be easily reused:

let imgs = document.querySelectorAll('body img');
[...imgs].forEach((img) => {
  img.setAttribute("style", "--bg: url(" + img.getAttribute('title') + ");");
});
img {
  padding: 5em;
  background:  var(--bg) 0 0 / cover ;
  box-shadow:inset 0 0 5em 
}
<img src="https://picsum.photos/id/1020/200/300" title="https://picsum.photos/id/1020/200/300">
<img src="https://picsum.photos/id/1025/200/300" title="https://picsum.photos/id/1025/200/300">
<img src="https://picsum.photos/id/1015/200/300" title="https://picsum.photos/id/1015/200/300">
<img src="https://picsum.photos/id/1025/200/300" title="https://picsum.photos/id/1025/200/300">
<img src="https://picsum.photos/id/1050/200/300" title="https://picsum.photos/id/1050/200/300">

untill the full table turns green at https://developer.mozilla.org/en-US/docs/Web/CSS/attr()

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129