2

So this is my code. I would like to display my image via data-bg on my div::after pseudoelement. I always get url, but I want display image.

body {
  background: red;
  width: 100vw;
  height: 100vh;
}

div:before {
  content: attr(data-bg);
  display: block;
}
<div data-bg="https://via.placeholder.com/150"></div>
connexo
  • 53,704
  • 14
  • 91
  • 128
kaluaaa
  • 47
  • 5
  • You cannot achieve that with CSS using `content: attr()`. `attr` retrieves only `strings`, it cannot generate an image from that, and it cannot be used inside (`url()`. Also note that `:before` is CSS 2.1 syntax; since 2010 we have CSS 3 and it's `::before` now. – connexo Oct 28 '21 at 10:09

2 Answers2

2

Code correction

There is a few errors in your code:

  • If you want to get the image at the requested url, you need to use url()
  • You are using content instead of background-image

Theoretically, your code should you like the following snippet with the corrections, don't forget to add a content and to size you pseudo-element.

body{
  background: red;
  width: 100vw;
  height: 100vh;
}

div:after{
  content: '';
  background-image: url(attr(data-bg));
  width: 150px;
  height: 150px;
  display: block;
}
<div data-bg='https://via.placeholder.com/150'></div>

Unfortunately, this won't work

The background-image property does not work well with url(attr()), so here is another snippet that does what you are trying to achieve. We're declaring a CSS variable for the element instead of using an HTML attribute. You may find more details in this related question

body{
  background: red;
  width: 100vw;
  height: 100vh;
}

div:after{
  content: '';
  background-image: var(--bg-image);
  width: 150px;
  height: 150px;
  display: block;
}
<div style="--bg-image: url('https://via.placeholder.com/150');"></div>
Oddrigue
  • 554
  • 5
  • 17
0
<html><head>
body{
  background: red;
  width: 100%;
  height: 100%;
}

div:after{
  content: '';
  background-image: var(--bg-image);
  width: 50%;
  height: 50%;
  display: block;
}
</head><body><div style="--bg-image: url('https://images.unsplash.com/photo-1453728013993-6d66e9c9123a?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dmlld3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&w=1000&q=80');"></div></body></html>`enter code here`
sathish
  • 59
  • 9
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 28 '21 at 10:40