Is it possible to represent a recursive variable using CSS?

When it comes to the html structure:

<body>
<div>
  <div>
    <div>
      ...
    </div>
  </div>
</div>
</body>

Is there a method to create recursive variables that utilize their parent's value:

body > div {
    --x: 1;
}

div {
    --x: calc(var(--x) + 1);
}

The provided code is invalid due to the fact that css variables cannot have dependency cycles. Here is another example of an invalid scenario:

body > div {
    --is-even: 0;
    --is-odd: 1;
}

div {
    --is-even: var(--is-odd);
    --is-odd: var(--is-even);
}

Are there alternative methods to represent such recursive variables in css?

Answer №1

Two CSS variables can be utilized to mimic recursive behavior and prevent cycle dependency.

Check out this example:

body {
  --x: 10;
}
.y {
  --y: calc(var(--x) + 1);
}
.x{
  --x: calc(var(--y) + 1);
}
.result {
  border-right:calc(1px * var(--y)) solid red;
  border-left:calc(1px * var(--x)) solid green;
  height:50px;
}
<body>
  <div class="y">
    <div class="x">
      <div class="y">
        <div class="x">
          <div class="y">
            <div class="x">
              <div class="y result">

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

Upon inspection of the last element, you will observe that border-right equals 17px (10 + 7) and border-left is 16px (10 + 6)

https://i.stack.imgur.com/pAdXI.png

This concept works well for elements with a 2-level structure, such as lists:

body {
  --x: 30;
}

ul { 
    font-size: calc(var(--x) * 1px);
    --y: calc(var(--x) - 8);
}

li {
  --x: calc(var(--y));
}
  <ul>level A
    <li>item 1
    </li>
    <li>item 2
      <ul>level B
        <li>item 2.1
          <ul>level C
            <li>item 2.1.1
            </li>
            <li>item 2.1.2
            </li>
          </ul>
        </li>
        <li>item 2.2
        </li>
      </ul>
    </li>
  </ul>

Answer №2

If you are unable to include additional elements in between (such as divs with different classes or ul/li), a straightforward method would be to manually set variables:

div { --x: 1 }
div div { --x: 2 }
div div div { --x: 3 }
/* ... */

In most cases, a document will only have a limited nesting depth, perhaps around 20, 50, or at most 100 levels – not thousands.

An interesting article discusses self-referencing variables. The author suggests the following approach:

:root {
  --x: 1;
}
div {
  --mixin: {
    --x: calc(var(--x) + 1);
  };
  @apply --mixin;
}

However, there is one catch mentioned by the author:

Currently, this feature requires Google Chrome with the experimental web platform features flag enabled for it to work.

UPDATE: Jan 2019 CSS @apply was discarded due to issues when applying mixins that contain other variables. We must wait until parent-var() becomes a standard in CSS.

For now, these are the available options:

  1. Manually define variables for each level
  2. Utilize two variables for alternating elements
  3. Await the implementation of parent-var()

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 to control the audio currentTime using Angular 2 component

Here is the HTML code snippet that creates an HTML5 audio element: <audio id ="audio2" controls="controls" autoplay="false" (canplay)="CanPlay($event)"> <source src="http://localhost:51657/Audio/1" type="audio/mp3"> </audio> In the ...

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

How can I implement a Mouse Over event listener for a FlexTable in GWT 1.7?

What is the best method to attach an event listener or handler to widgets in GWT 1.7? I have looked at similar questions on SO, but they appear to be outdated. How can I add a Hover listener to a FlexTable, disregarding the existing :hover in CSS? ...

Having trouble with the ".." shorthand not working in the HTML image directory path

My Website File Structure: -css - home.css -html - index.html -images - banner.png HTML Code: <!DOCTYPE html> <html lang="en"> <head> <title>myWebsite</title> <link rel="stylesheet" typ ...

Ways to position two images in the center

A website has been created by me and now I am looking to center text on the two images in the header. Here is the relevant code snippet: <div class="header"> <img src="css/title578145459.png" class="headerImage left&qu ...

Arranging content within columns according to their column position

As I design a grid with three columns, each grid box contains a div with a maximum width of 280px. Sometimes the grid columns exceed this width. To achieve my desired layout, I aim to align the content in the grid boxes so that the left column aligns to th ...

Displaying CSS image slideshow images side by side

Currently I am a student studying the fundamentals of HTML and CSS. My latest project involved creating a website showcasing my work from digital arts class, complete with a simple CSS slideshow. The original intention was to have each image displayed on i ...

If the header 1 contains a specific word in jQuery, then carry out an action

I have successfully used the contains() function before, but I've never incorporated it into an if-statement. The code below doesn't seem to be working as expected. Essentially, I want to check if H1 contains the word "true" and perform a certain ...

A bottom border that spans the entire width, complete with padding

I am attempting to create a uniform border for each item on my list. However, due to the nested structure of the list, I have used padding to achieve this. As a result, the appearance is as expected and behaves normally. Check out the JSFiddle Example C ...

Ways to Randomly Flip Divs

I have developed an application where all divs flip vertically on hover. I am looking for a way to make the flipping random without requiring a hover. Any ideas on how to achieve this? .vertical.flip-container { position: relative; float: left; ma ...

Scrolling to ID or Anchor using jQuery: Automatically scrolls to the top if already at the designated section

I've been on a quest to uncover the cause and solution for this issue. Lately, I've been utilizing $("#content").animate({scrollTop:$(#elementId).offset().top-183}, 600); to achieve smooth scrolling to an ID within a <div>. The number 18 ...

Items seem to vanish into thin air and become immovable when attempting to relocate them

I am attempting to create a unique grid layout with 3x3 dimensions, where each grid item represents a fragment of a single image. These items should have the capability to be dragged and dropped inside another 3x3 grid, in any desired sequence. I have hit ...

Interactive Map Displayed within a Pop-up Window

Recently, I developed a custom Google map where points are plotted and an HTML popup window appears when the image is clicked. Now, my goal is to open a file with JavaScript functions inside a lightbox/fancybox when a user clicks on an image. Below is th ...

Having Trouble Changing CSS with Rails Link_to CSS ID

While following the ruby on rails guide, I came across a specific way to write link_to's with a css id: <%= link_to "About", about_path, id: "third" %> I also attempted: <%= link_to ("About", :id => "third"), about_path %> Although ...

Obtaining the contents of a local directory with JavaScript

Currently, I am attempting to access the contents of a local folder using JavaScript. Despite my efforts with the Filesystem API, an error is consistently appearing: DOMException: It was determined that certain files are unsafe for access within a Web app ...

Is it possible for us to customize the angular material chip design to be in a rectangular shape

I recently implemented angular material chips as tags, but I was wondering if it's possible to customize the default circular design to a rectangle using CSS? ...

Responsive slide displays a unique number of items per slide depending

I created a logo slider using Bootstrap, similar to the one showcased here: http://jsfiddle.net/juddlyon/Q2TYv/10/. Currently, each slide in the slider displays 4 logos. I would like to make it responsive so that on smaller screens, only 2 logos are shown ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Adjusting offcanvas height in Bootstrap based on content

.cursor-pointer { cursor: pointer; } <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="690b06061d1a1d1d09c13c809e9afbcfc1792efeff8">[email protected]</a>/dist/js/bootstr ...

Troubleshooting: ngAnimate max-height failing to apply to specific element

Having integrated ngAnimate into a project to enhance animations, I've encountered some unusual behavior with a specific element. Let me provide some context: our website features a shop with categories and products within those categories. I am usin ...