CSS: 使用数据属性作为内容URL

CSS: Using data attribute as content URL

所以我有一个 div 允许我显示当前页面的二维码 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;
}

并像这样使用:

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

显然,要即时获得当前 URL,我必须将此 CSS 样式放在我页面的 <head> 中。我正在尝试将其移至样式表。

我想到了使用数据属性来指定 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>

所以,我的问题是,是否可以在样式表中加倍使用 content:url()attr(data-url)

.page-qr:before {
  content: url(attr(data-url)); /* Doesn't work, but you get the idea */
  height: 100px;
  width: 100px;
}

这是 css-values-3 中为 attr() 提议的功能。 CSS 看起来像这样:

.page-qr:before {
  content: attr(data-url url);
  height: 100px;
  width: 100px;
}

不幸的是there are no known implementations,所以这仍然是不可能的。

我只是偶然发现了同样的问题,但找到了使用 自定义属性 的解决方案。所以我们可以将任何允许的类型作为自定义 属性 值传递给它。然后你可以绝对定位它,如果那是你要找的。

你可以这样使用它:

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