Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Using data attribute as content URL

So I have a div that allows me to display a QR code of the current page URL:

.page-qr:before {
  content: url(https://chart.googleapis.com/chart?cht=qr&chs=100x100&chl=<?php echo current_page(); ?>?choe=UTF-8);
  height: 100px;
  width: 100px;
}

And used like:

<div class="page-qr"> </div>

Obviously, to get the current URL on-the-fly, I have to put this CSS styling in the <head> of my page. I am trying to move it to the stylesheet.

I had the idea to use a data attribute to specify the URL:

<div class="page-qr" data-url="https://chart.googleapis.com/chart?cht=qr&chs=100x100&chl=<?php echo current_page(); ?>?choe=UTF-8"> </div>

So, my question is, is it possible to double up the usage of content:url() and attr(data-url) in the stylesheet?

.page-qr:before {
  content: url(attr(data-url)); /* Doesn't work, but you get the idea */
  height: 100px;
  width: 100px;
}
like image 773
MultiDev Avatar asked Nov 23 '25 11:11

MultiDev


1 Answers

I just stumbled upon the same problem, but found a solution using custom properties. So we can pass any type that is allowed as a custom property value to it. Then you can absolute position it if that is what you look for.

You can use it like this:

HTML

<div style="--img-url: url('${imgUrl}')"></div>

CSS

div {
  position: relative;
}

div::before {
  position: absolute;
  top:0;
  left:0;
  width:100px;
  height:100px; 
  content: var(--img-url); 
}

See this post for further info

like image 53
radrex Avatar answered Nov 26 '25 04:11

radrex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!