CSS 通过数据图像属性设置背景图像 [英] CSS set background-image by data-image attr
问题描述
我有一些具有这种模式的元素:
<div data-image="{imageurl}" ...></div>
我想将此元素 background-image
设置为 data-image
.我测试了这个 CSS 代码:
div[数据图像] {边框:2px纯黑色;背景图片:属性(数据图片网址);}
边框显示正确但背景没有任何反应如何仅使用 css(不是 js 或 jq)修复此代码?
data-
属性(或一般的 attr()
方法)的一个很好的替代方案可以是使用自定义属性(MDN、csswg、css-tricks).
因为它们的值不限于字符串,我们可以传递任何允许作为自定义属性值的类型!
此外,您还可以通过交换样式表在运行时更新这些属性.
.kitten {宽度:525px;高度:252px;背景图像:var(--bg-image);}
<div class="kitten"style="--bg-image: url('http://placekitten.com/525/252');">
I have sort of elements with this pattern:
<div data-image="{imageurl}" ...></div>
I want to set this elements background-image
to data-image
. I test this CSS code:
div[data-image] {
border: 2px solid black;
background-image: attr(data-image url);
}
border show correctly but nothing happened for background How can do I fix this code only with css (not js or jq)?
a nice alternative to data-
attributes (or the attr()
approach in general) can be the use of custom properties (MDN, csswg, css-tricks).
as their values are not restricted to strings, we can pass around any type that is allowed as a custom property value!
also, you get the benefit of updating these properties at runtime, with a swap of a stylesheet.
.kitten {
width: 525px;
height: 252px;
background-image: var(--bg-image);
}
<div class="kitten"
style="--bg-image: url('http://placekitten.com/525/252');">
</div>
这篇关于CSS 通过数据图像属性设置背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!