Home > front end >  Data attribute in div element and display on ::after pseudoelement
Data attribute in div element and display on ::after pseudoelement

Time:10-29

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

<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=&ixlib=rb-1.2.1&w=1000&q=80');"></div></body></html>`enter code here`
  • Related