How can we extract CSS values from dynamic HTML attributes or classes to steer clear of inline styling?

It is common knowledge that inline styles are considered bad practice and may not be compatible with certain security policies, such as the Content Security Policy.

The ideal goal is to achieve this without relying on inline styles:

<?php
$spacer_height = 390; // a dynamic value obtained from user input
?>
<div class="spacer" style="height:<?php echo $spacer_height; ?>"></div>

This is what is desired:

HTML:

<?php
$spacer_height = 390; // a dynamic value from user input
?>
<div class="spacer spacerheight-<?php echo $spacer_height; ?>" data-height="<?php echo $spacer_height; ?>"></div>

External Stylesheet:

.spacer {
  height: spacer_height + "px"; // placeholder code for illustration
}

Is there a way to accomplish this using only CSS, without resorting to JavaScript or polyfills?

I came across a similar question from 5 years ago: CSS values using HTML5 data attribute

However, I am curious if there have been any advancements since then or if there exists a CSS-only solution that does not rely on attributes. Even a solution specifically tailored for handling integers would be helpful.

Edit: In case no alternative solution is available, a functional polyfill suggestion would also be appreciated.

Answer №1

If achieving the desired result using CSS alone is not yet possible (as the attr() function currently only returns a string value), here is a basic script that can replicate the functionality of attr(), by parsing the data and dynamically setting it using cssText.

Feel free to let me know if this meets your requirements.

window.addEventListener("load", function() {
    var mb = isMobile();
    var el = document.querySelectorAll('[data-css]');
    for (i = 0; i < el.length; i++) {
        var what = el[i].getAttribute('data-css');
        if (what) {
            what = what.split(',');
            el[i].style.cssText = what[0] + ': ' + ((mb) ? what[2] : what[1]) + 'px';
        }
    }
});

function isMobile() {
  //function that checks if user is on mobile etc.
  return false;  // returning false for this demo
}
html, body {
  margin: 0;
}

div {
    background-color: lightgreen;
    padding: 10px 0;
    height: auto;
    box-sizing: border-box;
}

div ~ div {
    margin-top: 10px;
}
<div data-css="height,60,30"></div>
<div></div>
<div></div>
<div data-css="height,60,30"></div>
<div></div>

Alternatively, you could consider implementing a server-side solution where you generate the necessary CSS rule and class, inserting them into the CSS file and markup respectively before sending them to the client.

Answer №2

It may be beneficial to move the dynamic component from being directly embedded into the HTML code and instead include it in a separate <style> section.

<style>
.spacer {
    height:<?php echo $spacer_height; ?>
}
</style>
<?php
$spacer_height = 390; // this value can change based on user input
?>
<div class="spacer"></div>

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

How can I make the Box div bigger or smaller?

My goal is to expand and collapse the slider div only for the box where the user clicks. I have achieved this functionality, but a problem arises when I click "read more" - all the boxes expand, which is not the desired behavior. I want only the specific b ...

Access menu options by hovering over the image

I am looking to create a hidden menu that only appears when I hover over an image. I attempted to follow a solution on Stackoverflow, but it did not work for me. Is there a way to achieve this using just CSS? Html: <nav class="navbar navbar-inverse na ...

Several radial progress charts in JavaScript

While attempting to recreate and update this chart, I successfully created a separate chart but encountered difficulties with achieving the second progress. The secondary chart <div id="radial-progress-vha"> <div class="circle-vha ...

The script is not functioning properly on the subpage

My JQuery code doesn't seem to work when I try to transfer text from selected rows in a table on a child page to the parent page using AJAX. However, if I create and set the table with its rows and cells directly in the HTML file, the JQuery code work ...

Is there a way to retrieve all jQuery-portlet data from a webpage?

I need help with creating a button that opens a dialog displaying all portlet data, including the column ID they belong to. The dialog should show the information in this format: col1: portlet title: Title1 portlet content: The Content of Title1.. port ...

Please enter the time in minutes and seconds only

Currently, I am attempting to determine a way to create an <input type="time"> field that exclusively shows minutes and seconds. Despite my efforts with time pickers, I have been unable to achieve the desired result. Does anyone have any suggestions ...

I am looking to loop through an array nested within a JSON object and display it in a table column using

Within my JSON data, there is an array that I need to loop through in <td> tags. The functionality I am working on involves creating a table based on user input. The user specifies the number of rows, input columns, and output columns. I have three a ...

Is there a way to adjust the size of the canvas element in HTML without compromising quality or resorting to zooming?

I'm currently working on a basic modeling application for the web. The main component of my app is a canvas element that I'm trying to size correctly. However, when I set the height and width using CSS, it scales the entire canvas and compromises ...

JavaScript takes the spotlight before CSS

Currently experiencing this issue in Chrome, although Firefox seems to be working fine so far. Here is a greatly simplified version of the problem: HTML: <div class="thumbnail"> <a href='#' id="clickMe">Click me!</a> </d ...

The page action icon is visible exclusively on the extension's page

Currently, I am delving into the world of creating chrome extensions. One interesting feature that caught my attention is page actions, which allows developers to display an icon within the address bar. Let me share with you a snippet of my code: First, i ...

Is it possible to swap out one div for another div from an external HTML page?

How can I replace a div with the id 'mainbox' in my 'index.html' page with another div found in the 'list-div.html' page? <body> <div id="divet"> Sempre caro mi fu quest'ermo colle, e questa si ...

php stop items from being loaded and instead use a trigger to load them

Having recently delved into the world of programming, I'm determined to accomplish the following task: <body> <div class="gallery"> <img src="photo_1.jpg"> <img src="photo_2.jpg"> <img src="photo_3.jpg"> <!-- trigg ...

PHP causing redirection problems on the list page

Working on PHP and fetched all data from the database to display on a listing page. Trying to show dynamic data in the listing but facing difficulty in redirecting to the listing page. Need help with checking the code. Below is my HTML code: <div clas ...

The symbols ♥ and ♦ in HTML are displaying as black on Android devices, despite being styled as red in the CSS

In the midst of my card game development using HTML, JS, and CSS on the Meteor platform. To represent the hearts suit, I utilize &hearts; and for diamonds, it's &diams;. The color scheme is crimson with color: #FF0000; in the CSS code. The fon ...

Utilizing a wysiwyg text editor in conjunction with Angular 2

I am currently implementing a wysiwyg feature in my Angular2 project. When I include the code in the index.html page (the root page), it functions correctly. However, when I try to use it in a child view HTML file, the CSS and JavaScript do not load prope ...

What is the best way to center an absolutely positioned div within Internet Explorer 7?

ENSURING PROPER LAYOUT CONTEXT I am working with a simple layout for my webpage. It consists of two divs that are both positioned absolutely, with one centered within the other. <div id="protocol_index_body_wrapper"> <div id="protocol_index_ ...

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...

Unable to adjust the canvas size or scale using Fabric.js

Is there a way to display a large canvas as a smaller one for better user interaction without compromising the size of the uploaded canvas later on? I'm currently working with Fabric.js and exploring the Canvas CSS trick that involves setting the widt ...

Acquiring the content between the start of a paragraph and a designated hyperlink with the help of jQuery

I'm currently working on a jQuery script to extract the text from within a paragraph starting from the beginning up to a specific link: <p> Lorem ipsum dolor sit amet, <a href="#">aliqua</a> consectetur adipiscing elit, sed do e ...

I've been attempting to adjust the currentTime of an HTML5 video element within a React JS environment, but for some reason it keeps reverting

Need help updating the currentTime of an HTML5 video element with a slider in React JS. My issue is that whenever I adjust the slider, the value resets to 0. The problem seems to be related to the handleChange function which updates the videoRef.current.cu ...