Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using data attributes in css before/after for a background image

So I have HTML markup that looks like this:

<a href="#" data-icon="data:image/png;base64,iVKAInsdal...">Some link</a>

Then I want to use that data-icon in my CSS to display as the base 64 background image. Something like:

a:before {
    content: "";
    width: 16px;
    height: 16px;
    padding-left: 16px;
    background: url(attr(data-icon)); // this doesn't work
}

Is there any way to do this?

like image 692
dmathisen Avatar asked Dec 01 '22 19:12

dmathisen


2 Answers

Try:

content: attr(data-icon);

Codepen

JsFiddle

This will only work for text based data attributes though and not images.

You can apply a normal background, but only content allows attr.

like image 20
Albzi Avatar answered Dec 04 '22 11:12

Albzi


This IS possible!

(but not how you may think)

a{
    background-image:url(https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRrlZZQ3MwNcconkIeLX3_nS_IV81gJ8rincQsipqXGsiBkPmCX);
    background-repeat:no-repeat;
    background-position:1000px 1000px;
}

a:before {
    content: '';
    width: 16px;
    height: 16px;
    padding-left: 16px;
    background-image: inherit;
    background-position:0px 0px;
}

Unfortunately what you are attempting to do will not work, attr is only applicable to the content property.

The only possible alternative would be to give the parent a background image, then set background-image on the pseudo element to inherit. If you set the parent elements background-position outside its boundaries then the psuedo elements to zero, it will give the same effect of no image on the parent, but an image on the psuedo.

like image 103
SW4 Avatar answered Dec 04 '22 11:12

SW4