What is the best way to insert an HTML data attribute string into a SCSS mixin using attr()?

I'm currently working on setting up a color scheme in SCSS that allows me to use the following HTML structure:

<div class="swatch" data-bg="green">...</div>

In my SCSS file, I have defined a mixin like this:

@function color($key: 'black') {
  @return map-get($colors, $key);
}

With this setup, if I pass background-color: color('green'), it will look for 'green': #009900 in the $colors map and return background-color: #009900; as the CSS output.

However, when I try to pass the value of the data-bg attribute into the color() SCSS mixin, it doesn't seem to work as expected. Here's how I tried to implement it:

.swatch[data-bg] {
  background-color: color(attr(data-bg));
}

This implementation fails to render the background-color line in the CSS at all. Ideally, I would expect the parsing to flow like this:

color(attr(data-bg))color('green')#009900

If you'd like to see the problem I'm facing, check out the "Brown" color swatch on this Codepen: https://codepen.io/rbrum/pen/axZLxw

I would greatly appreciate any assistance with this issue.

Answer №1

After encountering this question, I found a creative solution to my problem.

I decided to move away from using data- attributes and instead focused on utilizing class names for elements. When I want a specific background color, I simply assign a class like .bg-amber or .bg-purple. Here are the colors I have defined:

$colors: (
  'black': #000000,
  'white': #FFFFFF,
  // ...
  'amber': #FFBF00,
  'purple': #800080,
  // ...
);

To access a color more efficiently, I created a function that retrieves the value based on the color name:

@function c($key: 'black') {
  @return map-get($colors, $key);
}

Next, I created a mixin that applies a specified color as the background with an optional prefix for CSS attributes:

@mixin bg($color-name, $prefix: '') {
  .#{$prefix}#{$color-name} {
    background-color: c($color-name);
  }
}

If I need to use this in a single instance, I would implement it like this:

@include bg('amber', 'bg-');

This code generates the following output:

.bg-amber {
  background-color: #FFBF00;
}

Furthermore, I utilize an @each loop to automate this process for all colors in my list:

@each $color-name, $color-val in $colors {
  @include bg($color-name, 'bg-');
}

In addition, I introduced a "foreground" variation:

@mixin fg($color-name, $prefix: '') {
  .#{$prefix}#{$color-name} {
    color: c($color-name);
  }
}

This feature can be seamlessly integrated into the existing @each loop following the bg() application:

@each $color-name, $color-val in $colors {
  @include bg($color-name, 'bg-');
  @include fg($color-name, 'txt-');
}

Furthermore, this concept extends beyond background colors to encompass border colors, box shadows, and more.

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

Fixed position navbar toggler

Hey there! I currently have a centralized navbar layout for Desktop. However, my aim is to also center it on the mobile version. Basically, this navigation bar appears when scrolled downwards with icons like this. Therefore, I'm looking for assistan ...

Utilizing Bootstrap 4: Opting for <select> over tabs (<li>)

Is there a way to customize the appearance of Bootstrap tabs by replacing them with a dropdown select menu instead of the standard tab layout created with <ul> and <li> elements? I am working with a relatively small area (such as col-3) where ...

Turn off hover opacity effect for a specific image

Currently, I've implemented a hover opacity effect on my images using the following CSS: img { opacity: 1.0; filter: alpha(opacity=1.0); } img:hover { opacity: 0.6; filter: alpha(opacity=0.6); } However, I now have a specific image for whi ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

Looking to display or conceal a text box with a date picker based on the selection of a specific value from a drop-down menu

I have a dropdown with two options: Indian and Others. When I select Others, I want to display three textboxes - two with date pickers and one with a simple text input field. I have tried writing the following HTML code but I am unable to get the date pick ...

Utilizing Beautiful Soup in Python to Scrape HTML Data from a Search Engine Results Page

I'm attempting to extract hotel information from booking.com using Beautiful Soup. I am specifically looking for certain details from all the accommodations in Spain. Here is the search URL: URL Upon inspecting an accommodation on the result page us ...

Radio buttons in 'Block Style' functioning perfectly on all devices except for iPad

I am facing an issue with a group of radio buttons that I have styled to display as block elements, making them look like buttons while hiding the actual radio button itself. This setup works perfectly on Chrome and Firefox on desktops and Android tablets, ...

What is the method for incorporating text below font icons?

Having a bit of trouble here with my code snippet featuring 'font awesome' icons in circles. I'm looking to add text beneath each icon, but the alignment within the circle is proving to be a challenge. Check out the code in this link to see ...

Issue with Element's Response to JQuery Click Event

After pulling elements from the database in PHP, I utilized Jquery to add Elements to the page. Each button has two classes; one for controlling the GUI and another for handling the click event of that specific button. Here is the code snippet: echo " ...

I'm having an issue where my footer is getting cut off when I resize the browser and start side scrolling. Can

I designed a webpage with a footer that contains another div holding centered content. The footer is supposed to span the entire width, while the inner content div is set to 960px with a margin auto to center it. <footer> <div class="footer-in ...

What is the best way to input keys without losing focus?

I am facing an issue with an HTML <input> field that displays autocomplete suggestions while the user is typing. I want to create an automated test using Selenium, where the driver inputs keys and then verifies the contents of the autocomplete dropdo ...

How do I utilize the Material-UI slider's activated (CSS API) feature to conceal the shadows?

Can someone please explain to me how I can use the activated class to change the style of the thumb and hide its shadows? According to the official website, the activated class is applied to the track and thumb elements to trigger JSS nested styles when a ...

Obtain ID and Class details from an HTML webpage using VBA

A few months back, I developed a program in Excel VBA to extract specific information about the prices of my game collection from an HTML page. Initially, it worked perfectly fine but suddenly stopped functioning about a month ago. I'm struggling to f ...

Aligning two identical components within the same container when triggered by a single click

Currently, I am exploring Angular 2 and Typescript and have been developing a pager component for a table. The pager functions correctly, but I have encountered an issue with having two pagers - one above the table and one below it. When the next button on ...

Mastering the Art of Utilizing content_for and Rendering Partials in Rails 4

Recently, I discovered the power of utilizing content_for and found it to be incredibly useful. It may seem like I am making things more complicated than necessary, but my objective is: To create a custom header for the products#index page. As of now, I ...

Utilizing MUI for layering components vertically: A step-by-step guide

I am looking for a way to style a div differently on Desktop and Mobile devices: ------------------------------------------------------------------ | (icon) | (content) |(button here)| ----------------------------------------- ...

Instructions for inserting an anchor tag into the middle of a <p> element utilizing document.createElement("p")

When generating elements dynamically with JavaScript using document.createElement("p"), I am looking to create a paragraph element <p></p> that includes an anchor tag in the middle, creating a clickable link within the text. I aim to use JavaS ...

Using HTML5 input type number along with a regular expression pattern

In order to display only numbers and forward slashes in the input field with regex pattern, I attempted the following code: <input type="number" pattern="[0-9\/]*"> However, this code only shows the number pad from 0 to 9. How can I modify the ...

Text in SVG file misaligned at the edge

After creating an SVG with a base64 background image and two text areas for top and bottom texts, I encountered an issue on Internet Explorer and Edge. The problem is that the bottom text is aligned to the left instead of the center, and its position is in ...

Exploring CSS3 Border-Radius Compatibility with Internet Explorer 9

After creating a CSS3 gradient using ColorZilla, I noticed an issue with the DATA URI that seems to be causing problems. Check out my fiddle link here: http://jsfiddle.net/cY7Lp/. In WebKit & Firefox browsers, the rounded corners display correctly. Ho ...