What is the method for utilizing the data-etc attribute value of an element for CSS property values?

Is it possible to use multiple data attributes in a single CSS style?

I have created the following CSS, trying to utilize both data-letters and data-color, but it is not working as expected.

The data-color attribute should dictate the background color, while data-letters should control the content styling in the CSS.

body { font-family: sans-serif; }

[data-letters]:before {
    content: attr(data-letters);
    display: inline-block;
    font-size: 32px;
    width: 85px;
    height: 80px;
    line-height: 2.5em;
    text-align: center;
    border-radius: 50%;
    background: #95A73B;
    vertical-align: middle;
    margin-right: 1em;
    color: white;
    margin-top:  20px;
}
<p data-letters="PB" data-color="#c0227a"></p>

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing the appearance of the file input type using an image in HTML and CSS

Can you provide guidance on utilizing the image below? Is there an alternative approach to using: <input type="file" /> ...

Responsive Material-UI horizontal navigation bar

Hey there! I'm working on developing a UI using Material-UI, and I want to make it so that the menu can be collapsed into a slide-in style menu when accessed on a mobile device. Currently, I'm using tabs which allow for sliding left and right, b ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

I am unsure of the best method to position this using flex in Bootstrap 5

Introduction to Bootstrap 5 Challenge: Greetings! I am currently exploring Bootstrap 5 after a hiatus of two years, and I have encountered a problem. Despite reviewing the documentation on the official Bootstrap 5 website, I am unable to position the new c ...

Grids designed in the style of Pinterest

Seeking advice on aligning divs in a Pinterest-style layout. Currently, my setup looks like this: https://i.sstatic.net/erlho.png But I want it to look more like this: https://i.sstatic.net/K9FnD.png Would greatly appreciate any tips or suggestions on ho ...

Issue with Tailwind CSS: The 'overflow-y' property does not scroll all the way to the bottom when using 'top-[63px]'

I'm facing an issue with my Tailwind CSS code that is hindering me from scrolling to the bottom of an aside element. <body> <div> <nav class=" bg-white px-2 py-2.5 dark:bg-gray-800 sm:px-4 fixed w-full z-20 border-b borde ...

Is it possible to apply a specific CSS color to a row in Angular 9 mat-tables without having to individually set it in multiple locations?

I am working on a mat-table in Angular 9 where I need to implement a function that determines the CSS class for each row... getRowClass(item: Item): string { let class_ = ""; if (...condition1...) { ... } else { class_ ...

Is there a way to combine the input tag's name with a growing integer variable?

Within a while loop, I need to modify the names of input tags by concatenating them with an increasing integer variable. However, attempts to use the $ symbol have not yielded successful results. <html> <head> <meta http-equiv="Content- ...

How can I effectively develop a versatile user interface for a website using Ruby on Rails that is compatible with all

Currently, I am in the midst of developing a web application using Ruby on Rails. Occasionally, I encounter challenges with cross-browser compatibility when it comes to CSS and Javascript. Are there any strategies you recommend to reduce these issues dur ...

What steps can be taken to ensure that the popover div remains visible when clicking inside it in a "dismissible popover" using Twitter Bootstrap with the data-trigger attribute set to "

I am struggling with a dismissible popover that contains a text box. When I click inside the text box to type, it disappears due to the "data-trigger="focus". Is there a way for the div not to disappear when clicked inside intelligently? Here is the releva ...

Combining and integrating rows within a table

I have created a table with two columns labeled "Team" and "Members". My question is this: how can I add a new row when the plus icon in the Team column is clicked, and only add a row in the Members column when the plus icon in that column is clicked? & ...

JavaScript: a single function and two calls to Document.getElementById() results in both returning "undefined"

Within my JavaScript file, I have a function that utilizes two variables: choice and courseChosen. The latter variable must be converted into an object first. In the HTML, the tags courseName and courseInfo are used for choice and courseChosen respectively ...

Searching for the value of a JavaScript variable in a PHP DOMDocument

How can I retrieve a JavaScript value in PHP using the DOM? $dom = new DOMDocument(); $html ='<html> <body>Hello <b id="test">Hello World</b>.</body> <script> document.getElementById('test').innerHTML = ...

What could be causing the TailWind CSS Toggle to malfunction on my local server?

While working on designing a sidebar for a ToDo page using Tailwind CSS, I encountered an issue with implementing a toggle button for switching between dark mode and light mode. In order to achieve this functionality, I borrowed the toggling code snippet f ...

Listening to a sequence of mp3 tracks consecutively

I'm currently working on a project that involves playing a series of mp3 files consecutively. However, I've encountered an issue with my code snippet below: Here's the code snippet: function playAudio(){ var au = document.getElementById( ...

Struggling with JavaScript conditional statements

Currently, I am in the process of creating a login and registration panel using jQuery and PHP. Essentially, if there are any errors during registration, it sets certain form errors, redirects back to the registration page, the JavaScript identifies these ...

JavaScript button with an event listener to enable sorting functionality

I am looking to implement a button that will reset all the filters on my page. Any ideas? Currently, I have multiple radio buttons for filtering items based on price, size, and color. My goal is to create a reset button that will remove all filters and r ...

Why isn't a password appearing in the "generated-password" div from the password generator?

The function toIncludeCharacters() appears to be functioning correctly as it returns lowercase letters upon upload, but generatePassword() is currently producing a blank output. After clicking the "Generate Password" button, three blank outputs are return ...

Utilizing a div element within a loop to showcase content in a horizontal layout

I'm currently working on a project where I need to showcase YouTube links on a webpage, accompanied by brief descriptions. To achieve this, I am utilizing a repeater. Below is the item template I have implemented: <Item Template> <asp:Pane ...

The Firebase JQuery .on method is incrementally updating individual values in an array instead of updating them all simultaneously

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. I have implemented the jQuery .on method for this purpose. However, the values are being returned one by one from the array created for the order ...