Styling with CSS Variables and Transforming Elements

After conducting thorough research both on this platform and via Google, I have yet to find a solution to my query: "how can CSS variables be utilized in a CSS transform?"

Within the HTML header, three CSS variables and their fallback values are declared:

<!Doctype>
<html>
    <head>     
        <style>
              :root {
                     --AHItop      : -260px;
                     --AHIleft     :   90px;
                     --AHIRotation :  10deg;
                    }

The actual CSS code is as follows:

 .AHI
    {
        position        : absolute;
        top             : var(--AHItop);
        left            : var(--AHIleft);                   
        width           :  250px;
        height          :  540px;
        z-index         :    3;
    }

Within the Body of the HTML, a DIV element is created:

<body>
    <div style = "position: absolute; 
         left    : 0; 
         top     : 0;
         overflow: hidden;">

An image is then inserted into the DIV (followed by closing the DIV and body):

        <img 
            src     = "gaugesAHI.png"               
            class   = "AHI"         
        />
    </div>
</body>

Contained within the Script tags is a snippet of code that utilizes the CSS variables:

<script>
    var pitch = 10;
    const elementAHI = document.querySelector('.AHI');
    elementAHI.style.setProperty('--AHItop',    pitch * 5.7 - 10);
</script>

This results in the desired outcome. However, the main issue arises when attempting to implement a 'rotate' transform within the CSS, using:

transform       : rotate(var(--AHIrotate));

In the CSS and:

elementAHI.style.setProperty('--AHIrotate', pitch);

within the script. Various attempts were made using both IE and Chrome without success.

While not an expert in Javascript, I usually enjoy the challenge of problem-solving on my own. Yet, in this instance, I humbly seek assistance - any guidance provided will be greatly appreciated.

Thank you.

Answer №1

To address the issue at hand, an effective approach is to incorporate variables into the CSS and analyze their impact.

Initially, the variables are set as follows:

:root {
  --AHItop: -260px;
  --AHIleft: 90px;
  --AHIRotation: 10deg;
}

Consequently, the CSS translates to:

.AHI {
  position: absolute;
  top: -260px;
  left: 90px;
  width: 250px;
  height: 540px;
  z-index: 3;
  transform: rotate(10deg);
}

This configuration appears appropriate and functions correctly. Let's now explore the behavior of your JavaScript code.

var pitch = 10;
const elementAHI = document.querySelector('.AHI');
elementAHI.style.setProperty('--AHItop', pitch * 5.7 - 10);
elementAHI.style.setProperty('--AHIrotate', pitch);

The first two lines require no further analysis while the last two necessitate some calculation.

--AHItop = pitch * 5.7 - 10
--AHItop = 10 * 5.7 - 10
--AHItop = 57 - 10
--AHItop = 47

The subsequent line presents a simpler scenario:

--AHIrotate = pitch
--AHIrotate = 10

Upon substituting the updated variables back into the CSS, we obtain the following result:

.AHI {
  position: absolute;
  top: 47;
  left: 90px;
  width: 250px;
  height: 540px;
  z-index: 3;
  transform: rotate(10);
}

Here lies the problem—our units have been lost. --AHItop necessitates px, while --AHIrotat requires deg. This discrepancy can be easily rectified in the JavaScript code.

elementAHI.style.setProperty('--AHItop', (pitch * 5.7 - 10)+'px');
elementAHI.style.setProperty('--AHIrotate', pitch+'deg');

By implementing these modifications, it seems that the CSS should be able to function as intended.

I trust that this explanation clarifies the situation 🙂

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

Is there a method to construct this? It appears quite challenging to create the intricate lines

I want to achieve this specific layout, but I am unsure how to align the lines next to the boxes. Should I use display or position properties to accomplish this? Image illustrating my desired outcome ...

Showcasing a dynamically created JSON document on a basic web page

Looking for a solution to display the contents of a result.json file generated by my Java tool on a simple website. I am aware that accessing local files directly with JavaScript is not possible, so seeking alternative methods that do not involve using a w ...

Creating a masonry layout with uniform row heights

I am trying to achieve a masonry style layout for these cards in Bootstrap. The current setup has columns with the same height, but I want them to have fluid height and consistent margin spacing like the blue line shown below. I attempted to use .card-colu ...

Establish a comprehensive background for your Angular project

I've been struggling to figure out how to set a background image for my entire angular project. I've tried using global css and the app.component.css file, but it only sets the background for the component area. Here is a snippet from my global ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

Unable to locate the <router-view> component within VueRouter

I recently completed a project using Vue.js 3.2.13 and Vue-Router 4.0.14. Despite my efforts to ensure everything was set up correctly, I encountered an error in the browser that said "[Vue warn]: Failed to resolve component: router-view". The specific lin ...

Utilize JavaScript objects to convert subscripts into HTML elements

I am currently developing an Angular 1X application where all icon labels are stored in a JS object as shown below: var labels={ ........ iconlabel_o2:"O<sub>2</sub>", iconLabel_co2:"CO<sub>2</sub>", iconLabel_h20:"H<sub ...

How to Extract Calendar Week Numbers in React from a Specific Month

Is there anyone who can assist me in calculating the week numbers for a specific month? For instance, July is expected to have week numbers 26, 27, 28, 29, and 30. How can I accomplish this task and store the results in an array? Currently, I am only abl ...

I've been stuck on this for the past hour, trying to figure out why /js/bootstrap.min.js can't be located

I'm having an issue with the code in base.html while trying to create a bootstrap starter template. I copied it from bootstrap but when I run it, I get an error related to /js/bootstrap.min.js. Can someone help me figure out what's wrong? Thank y ...

Avoiding conflicts among jquery prototype/plugin methods

Imagine I have a primary JavaScript file on my website that includes the following code: $.fn.extend({ break: function(){ // Add your custom code here }, cut: function(){ // More code here }, // ...and many other methods }); When using t ...

A Step-by-Step Guide on Sending Response to ajaxError Callback in Perl

When working with JavaScript, I have a method of capturing errors that looks like this: $(document).ajaxError(function(event, jqxhr, settings, thrownError) { handleError(MSG_SAVE_ERROR); }); Now, my question is how can I retrieve an error message fro ...

Clicking on the overlay does not close the bootstrap collapsed toggle

I'm currently facing an issue where I need to add a listener that closes the menu when clicked away. The code snippet below shows my attempt at solving this problem: $("body").click(function(e){ var $box1 = $('.navbar-toggle'); var $b ...

Position a div element on top of Google Maps to create a floating

Currently working on a website and attempting to add shadows over Google Maps by using a <div> element for a shadow effect: Unfortunately, the desired effect is not being achieved. This is the current CSS code in use: html { height: 100% } body ...

substitute a component with a different one if it is present

I'm currently working on a script that will automatically replace one element with another as soon as it is created, even when the page loads. Despite my attempts to use MutationObserver, I haven't been successful. var target = document.querySe ...

What is the best way to dynamically add a stylesheet using JavaScript/jQuery?

I've been scouring the web for a solution to a particular issue, but so far I'm coming up empty-handed. We're working with Umbraco CMS for a client's website, and it seems we can't insert conditional comments in the <head> se ...

JavaScript - Display all comments

Here's the structure of my JSON data: { "comment_ds": [ { "c_user": [ "Alice", "Alice", "Alice", "Alice" ...

Ruby on Rails allows for the selection of values in a dropdown menu to trigger the visibility of different sections of HTML

As a newcomer to Rails, I was able to successfully implement the onclick function for a f.checkbox element. Now, my challenge lies in achieving a similar functionality for a f.select element within a _form. Below is the code snippet that works for a chec ...

Events for focusing and blurring top level windows

I'm encountering an issue with a basic frameset setup <frameset rows="100, 200"> <FRAME name="listener" src="frame1.html"> <FRAME name="content" src="http://www.someexternalurl.com/"> </frameset> Within the listener ...

The jQuery validation applied to the data submission per post is not functioning as expected as the $_POST variable is appearing empty

I'm facing an issue with Jquery, AJAX, and field validation. Although the validation and redirect are working fine, I'm having trouble retrieving values from fields in the $_POST array. Below is the start tag of the form: <form class="smart ...

Tips for utilizing the onClick function in jQuery on an element nested within a div that was dynamically added using jQuery beforehand

I have added some elements inside a div with the class .display_noti like this: $(document).ready(function(){ setTimeout(done,200); }); function done() { setTimeout(updates, 200); // Call updates in 200ms } function updates(){ $.getJSON("notificatio ...