How can I concatenate the CSS attr() selector with static text in a url() field?
The HTML I use:
<div image='/Require/static.png'></div> //Example 2
<div image='static.png'></div> //Example 3, 4, 5
For example:
//image attribute contains the image name (and prefix location when needed, see example 2)
div[image]:before {
background-image: url('/Image/static.png'); //Works
background-image: url(attr(image)); // Works
background-image: url('/Image/' attr(image)); //Fails
background-image: url('/Image/' #attr(image)); //Fails
background-image: url('/Image/' {attr(image)); //Fails
}
So - if it is possible - How can I achieve this?
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.
CSS performs concatenation without using any operator (e.g. +, &, etc). Keep your strings in quotes combine the strings, attr, var, etc into one line. Examples: url('not/very' '/useful/concatenation'); // not/very/useful/concatentation.
The url() CSS function is used to include a file. The parameter is an absolute URL, a relative URL, a blob URL, or a data URL. The url() function can be passed as a parameter of another CSS functions, like the attr() function.
Usage is simple — you insert the path to the image you want to include in your page inside the brackets of url() , for example: background-image: url('images/my-image. png'); Note about formatting: The quotes around the URL can be either single or double quotes, and they are optional.
It is not possible to create a composite url()
value out of two or more strings. On top of the legacy url()
value, which isn't even a proper CSS function (see Is there a way to interpolate CSS variables with url()? — which means you can't even do this with custom properties), the proper CSS function version of url()
as defined in css-values-3 only accepts a single string.1
You can concatenate multiple strings in a content
declaration, but that is a feature of the content
property, not of strings in CSS.
1Since url()
accepts a single string, this does mean that a single attr()
can be used as a URL value, also new to css-values-3, as attr(image url)
... except browser support is nonexistent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With