Effective Methods for Implementing CSS Variables within nth-child Selectors

Objective: To pass a variable successfully as a parameter to nth-child. The task is to make the third line turn green in the example provided.

Dilemma: Currently, the parameter is being disregarded as a variable.

Inquiry: Is achieving this possible? If so, what adjustments need to be made?

Code Sample:

:root {
  --n: 3;
}
div p:nth-child(var(--n)) {
  background: green;
  padding: 10px;
}
<div>
  <p>a</p>
  <p>b</p>
  <p>c</p>
</div>

Answer №1

Utilizing CSS custom properties is restricted to being used in declarations, specifically after the :. It's important to note that these custom properties cannot be applied in selectors or media queries.

This limitation highlights why it's inaccurate to refer to them as CSS "variables".

However, styles can be modified with Javascript:

const dynamicStyles = document.getElementById('dynamicStyles');

const n = getComputedStyle(document.documentElement).getPropertyValue('--n');

dynamicStyles.textContent = `
div p:nth-child(${n}) {
  background: green;
  padding: 10px;
}
`;
:root {
  --n: 3;
}
<style id="dynamicStyles"></style>
<div>
  <p>a</p>
  <p>b</p>
  <p>c</p>
</div>

Answer №2

Exploring the limitations of CSS, let's delve into this scenario: what color would the third p element be?

<div>
  <p>a</p>
  <p>b</p>
  <p>c</p>
</div>
:root {
  --n: 3;
}
p {
  background: cyan;
}
p:nth-child(var(--n)) {
  background: green;
  :root:has(&) {
    --n: 1;
  }
}

If --n is set to 3, the third p element will be green. If --n is 1, then it will be cyan. This cycle continues.

Answer №3

If you're looking to achieve this effect using only CSS, unfortunately that's not possible. However, you can create a JavaScript function to help with the task.

The following function will retrieve the value '3' from your :root{}:

getComputedStyle(document.documentElement)
    .getPropertyValue('--n');

Since JavaScript cannot be directly placed in CSS files, you will need to implement this in your HTML file. Your objective is to encapsulate an html style tag around the variable obtained from this function:

<script>
document.getElementById('custom-container'); // Select the div container

node.innerHTML('<style> #custom-container p:nth-child('); // Wrap style around the variable

getComputedStyle(document.documentElement)
.getPropertyValue('--n'); // Obtain your variable, which in this case is '3'

node.innerHTML('){background: green;padding: 10px;}</style>'); // Close the wrapping and define the style
</script>

<div id="custom-container"> <!-- Add an ID to mark your div container -->
  <p>a</p>
  <p>b</p>
  <p>c</p>
</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

Challenges with Aligning Panels in Column 6

My initial encounter with bootstrap was interesting. I attempted to have two panels placed side by side using the col-lg-6 class. The left panel was meant to be a link to an article, along with an image, while the right panel would serve as a signup/login ...

Center the content of the HTML body

Despite my best efforts, I seem to be making a mistake somewhere. While creating a bootstrap website at , the site appears well and aligned in the center. However, when I try to adjust the screen size to less than 850px or even smaller, all the content shi ...

Concealing specific DIV elements (unfortunately not nested)

Currently, I am dealing with pre-existing code that is automatically generated and needs to adhere to a specific format: <div id="TITLE1"></div> <div id="div-1"></div> <div id="div-2"></div> <div id="div-3"></d ...

What could be causing my Link to malfunction in my about.js file?

I've encountered an issue where clicking the link in my app doesn't produce any result, and I'm unsure of the cause. Below is the content of my app.js file: import './App.css'; import {BrowserRouter as Router, Routes, Route} from ...

Placing a button at the bottom of a bootstrap well

Hey there, I'm facing an issue with the button positioning. I really need the button to be placed at the bottom of the well, but for some reason, it keeps showing up next to the image instead. This is what's happening: the button is ending up be ...

search engine optimized for easy input via keyboard

I have successfully incorporated AJAX search functionality into my project, inspired by this example here. The unique feature of this implementation is the ability to navigate through search results using the TAB key. The structure of my search results tab ...

Adjust element based on the position of another element (sticky)

Is it possible to rotate a text block so that it remains anchored to the bottom of a red rectangle, even when the rectangle is rotated? Similar to how it works in Figma, but simpler. For example, if I rotate the rectangle by 180 degrees, the text should be ...

Creating a tab resizing effect similar to Chrome using only CSS

I am attempting to design tabs that can dynamically resize similar to how Chrome tabs behave. However, I am uncertain if achieving this functionality is possible without relying on JavaScript. Browser compatibility is not a concern for me; my main goal is ...

Show product name when hovering over the image

Trying to achieve a hover effect where product titles appear in a contained box when hovering over the product image on the bottom overlay, instead of below the image itself. Tried CSS code recommended by Shopify, but it had no effect: <noscript> ...

What is the reason for font names appearing yellow rather than blue in the "font-family" property?

Whenever I experiment with different font names, I notice that some fonts turn blue while others remain yellow. Can anyone clarify why this is happening? font-family: Arial, Helvetica, sans-serif; font-size:12px; font-weight:normal; ...

How to Enhance Your MUI DataGrid Rows with Borders

Trying to customize the borders of Material UI DataGrid rows to achieve a design similar to this screenshot (with some info censored): https://i.stack.imgur.com/0xRFd.png The issue I'm facing is that I'm unable to display the right border correc ...

Browser and contexmenu intersecting halfway

I have successfully implemented a custom context menu in my HTML project. It functions well, but I am facing an issue where half of the menu appears off-screen to the right. Is there a way to detect this and reposition the menu above the mouse pointer? He ...

Displaying items in the shopping cart across two separate columns

I have a website located at Within that page, I have included the Cart table using a woocommerce shortcode. Currently, the cart table is positioned below the billing details and payment options section. My goal is to move this cart table to be situated ...

Learn how to swap out the traditional "back to top" button with a customized image and make it slide onto or off the page instead of simply fading in and out

As a newcomer, I am trying to replicate a unique "back to top" effect that caught my eye on another website. Instead of the traditional fade-in approach when scrolling down, the "back to top" image in question elegantly slides out from the bottom right c ...

The Bootstrap 4 grid appears to be malfunctioning as the columns are not displaying next to each other as expected

I've implemented the code below in an attempt to achieve the desired layout shown in the image, but instead, I'm getting a different outcome. Can someone help me figure out what I might be doing wrong with the Boostrap 4 grid system? I'm co ...

Fluidly move through spaces where subsequent elements align to the top level

In the black container, there is an {overflow:hidden;} CSS property applied The yellow blocks are ordered in code according to the numbers and have {float:left;} I am aiming for the 5th element to align with the element above it: However, currently this ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

What is the best way to make a block fill 100% of a container-fluid?

Here is a block: <div class="container-fluid"> <div class="content_wrapper"> </div> </div> What's the best way to display the .content_wrapper block with 100% content width and margins from the body borders? ...

Changing the background of one div by dragging and dropping a colored div using jQuery

Looking at my HTML code, I have 4 <div> elements - 2 represent doors and 2 represent colors based on their respective id attributes. My goal is to enable users to drag any color to either door (e.g. blue on the left door and black on the right) and ...

Interactive Sideways Navigation Bar

showcases a sleek horizontal scrolling menu on mobile devices. I aim to replicate this functionality for a website I'm redesigning that features extensive navigation elements. Key Features: Left and right scroll button options Centered list item op ...