Is it possible to leverage the attr() function to extract the z-index value, a CSS property, to incorporate it within the calc() function in my stylesheet?

How can I dynamically adjust the position of a specific div element with the id "test" on my webpage based on its z-index using CSS's calc() and attr() functions? I want the position to change proportionally when the z-index changes.

It appears that the attr(zIndex) value is always evaluated as one, causing the element to remain in place regardless of the zIndex modifications. Is there a way to correctly access CSS values within the style definition itself, or should I handle this task entirely in JavaScript?

<!DOCTYPE html>
<html>
    <head>
        <title>zLinkTestPage</title>
        <style>
            body { background-color: #000000; }
            div { margin: 0px; padding: 0px; border-width: 0px; display: block; }
            #test {
                position: absolute;
                top: 0px;
                left: calc( attr(zIndex) * 10px );/*This line is the one in question*/
                background-color: #ff0000;
                z-index: 0;
                width: 144px; height: 288px;
            }
            #ref {
                position: absolute;
                top: 0px;
                left: 0px;
                background-color: #00ff00;
                z-index: 1;
                width: 288px; height: 144px;
            }
        </style>
    </head>
    <body>
        <div id="ref">Reference div</div>
        <div id="test" onmouseenter="moveZ(2);" onmouseleave="moveZ(-2);"><br /><br /><br /><br /><br /><br /><br /><br />Test div</div>
    </body>
    <script type="text/javascript">
        function moveZ(amount) {
            var box = document.getElementById("test");
            var curZ = box.style.zIndex;
            if(curZ == "") {
                //console.log((typeof curZ) + " curZ=" + curZ);
                curZ = 0; //because, for some reason, the initial value of any CSS property when accessed by JavaScript always seems to be null of some sort...
                //console.log((typeof curZ) + " curZ=" + curZ);
            }
            else {
                //console.log((typeof curZ) + " curZ=" + curZ);
                curZ = parseInt(curZ);
                //console.log((typeof curZ) + " curZ=" + curZ);
            }
            var newZ = curZ + amount;
            box.style.zIndex = newZ;
        }
    </script>
</html>

This challenge is part of my learning process, aimed at creating more advanced projects in the future.

Answer №1

I believe achieving that solely with CSS is not possible. However, you can utilize the HTML attributes of an element within the CSS content property and also refer to HTML attributes in CSS selectors.

For instance, by incorporating a custom attribute like zIndex (not the CSS property z-index) or creating a data-zIndex, you can then reference it in the content attribute like so:

#test:after {
  content: attr(data-zIndex);
  background: white;
  color: black;
  padding: 1em;
  display: inline-block;
}

Alternatively, you can employ a CSS selector to target elements based on the value of the attribute, for example...

#test[data-zIndex="0"]:after {
  border-radius: 1em;
}

#test[data-zIndex="2"]:after {
  background: yellow;
}

You can view a demonstration showcasing these adjustments.

function moveZ(amount) {
  var box = document.getElementById("test");
  var curZ = box.getAttribute('data-zIndex');
  if (curZ == "") {
    //console.log((typeof curZ) + " curZ=" + curZ);
    curZ = 0; //because, for some reason, the initial value of any CSS property when accessed by JavaScript always seems to be null of some sort...
    //console.log((typeof curZ) + " curZ=" + curZ);
  } else {
    //console.log((typeof curZ) + " curZ=" + curZ);
    curZ = parseInt(curZ);
    //console.log((typeof curZ) + " curZ=" + curZ);
  }
  var newZ = curZ + amount;
  box.setAttribute('data-zIndex',newZ);
}
body {
  background-color: #000000;
}

div {
  margin: 0px;
  padding: 0px;
  border-width: 0px;
  display: block;
}

#test {
  position: absolute;
  top: 0px;
  left: calc( attr(zIndex) * 10px);
  /*This line is the one in question*/
  background-color: #ff0000;
  z-index: 0;
  width: 144px;
  height: 288px;
}

#test:after {
  content: attr(data-zIndex);
  background: white;
  color: black;
  padding: 1em;
  display: inline-block;
}

#test[data-zIndex="0"]:after {
  border-radius: 1em;
}

#test[data-zIndex="2"]:after {
  background: yellow;
}

#ref {
  position: absolute;
  top: 0px;
  left: 0px;
  background-color: #00ff00;
  z-index: 1;
  width: 288px;
  height: 144px;
}
<div id="ref">Reference div</div>
<div id="test" data-zIndex='0' onmouseenter="moveZ(2);" onmouseleave="moveZ(-2);"><br /><br /><br /><br /><br /><br /><br /><br />Test div</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

Executing PHP code within the .html() jQuery function

Are you trying to update a link's text content dynamically using jQuery? <a id="btnExistReceiver" class="btn btn-app"> <i class="fa fa-user"></i> <?= __('Existing Receiver') ?> ...

Issue with Navigation menu dropdown not functioning properly on Angular version 12 with Bootstrap 5

I am attempting to integrate bootstrap with Angular through a CDN. Below is the content of my index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Laboratorio Sigma< ...

What is the best way to utilize HTTP headers in caching dynamic CSS?

Although this question is similar to this one on Stack Overflow, the provided solution does not seem to be effective. I am currently working on a WordPress plugin where I need to generate a dynamic CSS file. Below is the code snippet I am using: public s ...

Adjusting the orientation of an image using CSS3 depending on the position of the mouse

So I discovered that it's possible to make an image pan left or right using CSS3. Here's an example: HTML <html> <div> <img src="pic.png" class="pan"> </div </html> CSS .pan:hover { margin-right: -50px; } That& ...

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

Issue with CSS: Hover effect causing unexpected additional white space

My main goal is to implement a hover effect that covers an entire section, but I'm facing some challenges. When I hover over my products, it doesn't behave as expected and adds extra white space below while not covering the section properly. Thi ...

The react boolean attribute is malfunctioning and the video is not playing automatically

I have a React component with a <video> element that includes the autoplay attribute. <video autoplay muted src="/vids/vid.mp4"> However, it does not work as expected. Interestingly, when I set autoplay="true", it starts wo ...

`I am facing issues with class binding in Vue 3 when using SwiperJS`

Currently, I am working with Vue 3 along with swiperjs. I have encountered a problem related to the v-bind:class behavior in my project. The issue arises when transitioning to the second slide, where the !h-auto class does not get applied as expected. St ...

Wheel of fortune - The chosen option does not align with the indicator

I am looking to create a game similar to a "Spinning Wheel" where users can select three possible outcomes and then spin the wheel. If any of the chosen three options appears when the wheel stops, the user wins. In the demo provided below, you may notice ...

Styling JQuery UI Selectable with Custom CSS

I've managed to incorporate JQuery UI Selectable into my project, but I'm looking to apply a unique style to the selected items. Despite knowing that I can use the following CSS: .ui-selected{ background-color:orange; } I actually prefer to ...

What is the best way to evenly divide divs vertically on a Bootstrap website?

I am currently working on a responsive page design and have come across this useful resource: http://www.bootply.com/2sfiCehqac My main objective is to ensure that when the screen size is medium or large: 1) div_left and div_right (orange and blue) adjus ...

Looking to showcase information in a list format using CSS?

This is how the data appears when it's rendered: https://i.sstatic.net/M0m2u.png In the above display, you can observe that the data is shown next to each other. I am curious if it is possible to use CSS to present the text in a list format? Below ...

showcasing a row of 10 items all at once

How do I make my bubble chart responsive? I want to display only 10 bubbles for large screens and have the number of bubbles per row decrease as the screen size gets smaller. I initially tried setting the width of each bubble to 10%, but it didn't wor ...

What is the best way to find a specific class within a CSS file using Visual Studio Code?

Currently, I am working with a bootstrap template on my webpage. I am interested in personalizing specific sections of the design, but unfortunately, I am having trouble identifying the relevant CSS rules within the extensive .css file. My research online ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...

Maintaining the image's aspect ratio using the Next Image component

Currently, I am using Next's Image component to display a logo. Although the image itself is 1843x550 px, I have specified the width and height properties to adjust it to fit within a space of 83x24 px. However, due to a slightly different aspect rati ...

Ways to ensure a <div> element adjusts its height based on inner content dimensions

When using buttons in a chatbot that have text which changes based on selected options, I've encountered an issue where the text length sometimes exceeds the button's space. I'm looking for a way to make the containing div automatically adj ...

Escape special characters like < and > automatically

Is there a way to display text on a website without needing to manually check for special characters like < and >? I am looking for a simple solution that will allow me to copy text from programs like notepad directly into Visual Studio. I experimen ...

The background image is not displaying correctly

I've been struggling to add a background to the menu section at the top of my webpage. I uploaded the image to www.ra3manifesto.co.nf and want the logo, h1, and menu bar to be placed on top of it. I attempted to set this background using the following ...

"Add a new style sheet to the homepage of your WordPress site using the

I have been attempting to utilize a separate style sheet in order to customize the front page of my wordpress website. Despite several attempts, I have not had any success. Below is the current code that I am working with: add_action('wp_enqueue_styl ...