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

The (window).keyup() function fails to trigger after launching a video within an iframe

Here is a code snippet that I am using: $(window).keyup(function(event) { console.log('hello'); }); The above code works perfectly on the page. However, when I try to open a full view in a video iframe from the same page, the ke ...

Tips for utilizing the <base> element in HTML5 for selective anchor tags

I only have one base tag in the head section of my HTML document, and there are two anchor tags with different URLs as shown below: <!DOCTYPE html> <html lang="en"> <head> <base href="https://www.youtube.com"/> </head> &l ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...

Is there a method to incorporate a scroll event into the ng-multi-selectdropdown, a npm package?

Query: I need to incorporate a scroll event in the given html code that triggers when the div is scrolled. However, I am facing issues with implementing a scroll event that works when the elements are being scrolled. <ng-mult ...

What is the best way to showcase SVG code as an image using Vuejs?

My API is returning an SVG image as ASCII text code, which I am trying to display on my page. However, instead of the image, I just see a blank space. You can view my attempted solution in this JSFiddle: https://jsfiddle.net/c0p4ku78/ The key parts of th ...

Unveil the modules of a Node.js NPM application

I have a Node application that is used as an npm module and serves as a dependency in the package.json file of another Node application. This application needs to grant access to internal modules to the app utilizing my package as a dependency. All these m ...

The value of a select box cannot be retrieved until it has been clicked on

I am working with a selectBox element in my code: <select class="span2" name="filterYear" id="filterYear" style="margin-right:10px;"> <% for (var i = 0; i < years.length; i++) { %> <% if (years[i] == selectedYear) { %> ...

Storing numerous JSON records into an array by parsing them from a file

As a beginner in JS programming, I have a question that may seem trivial. Despite hours of searching online, I haven't been able to find a solution that works for me. I am dealing with multiple JSON feeds where each URL provides a multilayer JSON rec ...

Tips for aligning an icon vertically within a span tag

I have a span similar to this: <span class="indicator"></span> Sometimes this span contains numbers like: <span class="indicator"> <span>10</span> </span> Other times it may display Kendo-UI icons, such as: < ...

Guide for displaying SQL data in an HTML table

I am currently working on transferring my SQL data to an HTML format. The code I have so far is not functioning as expected. I attempted to include HTML within my PHP code, and now I am considering if it would be better to do it the other way around (emb ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants > ...

Using ion-icon inside a clickable ion-card while applying float: right does not render properly

I am facing an issue with a list of ion-cards that have clickable icons appearing when you hover over them. The problem is that due to the floating nature of the icons, they are not positioned correctly (as shown in the image below) and end up getting cove ...

Demonstrate complete attendance by detailing specific days of presence and days of absence within a specified date range

In order to track the attendance of employees, I have a log that records when an employee is present or absent on specific dates within a given interval. Let's consider the following date range: $from = "2019-03-01"; $to = "2019-03-05"; Here is a ...

Why is the jQuery ajax file uploading feature failing to function properly in the IE9 standard mode?

My file upload function works well in browsers like Chrome and IE10, but encountered an issue when tested on IE9. The Action controller reported that Request.Files were returning files with '0' length. I'm unsure if this problem is related ...

Tips for looping through client.get from the Twitter API with node.js and express

I am in the process of developing an application that can download a specific number of tweets. For this project, I am utilizing node.js and express() within my server.js file. To retrieve data from the Twitter API, I have set up a route app.get('/ap ...

Display the number of likes without having to refresh the page

On my website, there is a like/unlike post feature. When I click the like button, I want the value of check2 to appear next to the like button without needing to refresh the page. Currently, after clicking like, the data is inserted but only appears after ...

What is the best way to access an external array using ng-repeat in AngularJS?

My dataset consists of 3 separate arrays. "areas": { "default": [ { "area": "Master Bedroom", "uuid": "986e3f42-1797-49ae-b060-181a33b9", "description": "", "new": [ { "value": "986e3f42-1797-49ae-b060-181a3 ...

Setting the font-size in HTML/CSS to dynamically adjust and fill the entire width and height of its

I'm trying to make a <div> element adjust its size based on the browser window. Within this <div>, there is a paragraph of text: <div style="width:80%; height:80%; margin:10%;"> <p>Paragraph of text. Paragraph of text. Pa ...

Managing multiple arrays in asynchronous functions in node.js

I am facing an issue with a large array (10K) that I need to split. I tried following this method: and it worked perfectly. However, I now need to pass the separated arrays to a request function and await the response before passing it to savetodb. Could ...

"Learn the process of incorporating a trendline into a line chart using Highcharts by manipulating the

I am facing difficulties in creating a trend line for a line chart. I have tried some old solutions but they did not work for me. Below is my current code: { "key": "003", "title": "Detections", "ty ...