Summary:
Currently, it is not possible. (As of June 2024) no browser supports using the attr()
function for anything beyond the content:
property in ::before
and ::after
pseudo-elements:
Context:
- The CSS
attr()
function theoretically allows you to utilize any DOM element attribute within a CSS property value.
- Currently, as of early 2022, the
attr()
function can only be used with the content:
property, limited to the ::before
and ::after
pseudo-elements.
- However, there is a way to combine multiple attributes within the
content:
property, such as:
body { font-family: sans-serif; }
[data-letters]::before {
content: attr(data-letters) ' ' attr(data-color);
display: inline-block;
font-size: 32px;
line-height: 2.5em;
text-align: center;
border-radius: 50%;
background: #95A73B;
vertical-align: middle;
color: white;
}
<p data-letters="PB" data-color="#c0227a"></p>
...however, this may not meet your requirements.
Keep in mind that the attr()
function in CSS conceptually returns an arbitrary text string value, rather than a "typed" value.
- Therefore, a string like "
#aabbcc
" is different from a CSS color-typed value #aabbcc
, which is one reason why utilizing color: attr(data-color);
is not feasible at present.
- Even if browsers supported
color: attr(data-color);
, it would essentially translate to color: "#aabbcc"
instead of color: #aabbcc
, making it invalid even if technically supported.
One speculation is that browsers hesitate to enable attr()
for other properties due to the possibility of achieving similar outcomes by setting an inline style=""
attribute on the element, except for scenarios involving ::before
and ::after
elements where direct mapping to a DOM element doesn't exist.
If you wish to monitor progress on implementation:
Options:
As an alternative, using an inline style=""
attribute to specify properties on a per-element basis is currently viable; when employing custom properties via inline style, these can be utilized in style rules of any ::before
and ::after
pseudo-elements without necessitating explicit styling on their parent elements:
body { font-family: sans-serif; }
[data-letters]:before {
content: attr(data-letters);
display: inline-block;
font-size: 32px;
line-height: 2.5em;
text-align: center;
border-radius: 50%;
background-color: var(--my-color);
vertical-align: middle;
color: white;
}
<p style="--my-color: #c0227a;" data-letters="PB"></p>
However, this approach entails duplicating values in both data-
attributes and within the style=""
attribute, which might seem cumbersome and inelegant.