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

Trouble with Displaying 3rd Level JQuery Dropdown Menu

Currently working on implementing a 3 level dropdown feature. I have been using a third-party responsive menu in Opencart and it's been working well. You can see a demo of it here: Unfortunately, Opencart does not natively support 3 level categories, ...

Included adaptable background-images in the upload

Recently, I developed a RoR based app/website that allows clients to upload their own background image to the cover page. Although the current setup works well with a single image, I am aiming to enhance the site's responsiveness by enabling clients t ...

Looking to dynamically set a background image using data fetched from an API in a ReactJS project

Looking to incorporate a background image from an API response in ReactJS Here is some sample code: useEffect(() => { axios.get(`https://apiaddress=${API_KEY}`) .then(res=>{ console.log(res); setRetrieved(res.data); console.log(retrieved ...

Despite being positioned absolutely, they are able to make z-index work effectively

Currently, I am facing an issue with two elements in my design. The first element consists of dotted circles that should have a z-index of -999 so they remain in the background entirely. The second element is a login form that needs to have a z-index of 99 ...

Desktop Safari displays Font-awesome icons with trimmed corners using a border-radius of 50%

While working on incorporating font awesome share icons into my project, I encountered an issue with getting a circle around them. After exploring various approaches, I opted for a CSS solution. Using React FontAwesome posed some challenges that led me to ...

Adjust the alignment of two headers with varying sizes

Can someone provide guidance on aligning two headers of different sizes (e.g. h3 and h5) based on their bottom edges, making them appear like a cohesive group in a sentence format? The current code snippet I am working with is as follows: ...

How do I apply a xPage page style using the styleClass attribute instead of directly using the style attribute

Would like to know how to change the background color of an entire page using styleClass instead of directly in the xp:view tag? Here's an example that works: <xp:view xmlns:xp="http://www.ibm.com/xsp/core" style="background-color:#f1f1f1;"> ...

Can you use CSS to dynamically modify the font of radio buttons?

After attempting to achieve this using jquery (referencing How do I get javascript to run more than once?), some individuals suggested that CSS could provide an easier solution. Currently, I have JS code that dynamically applies and removes the ez-selected ...

How can I convert a PHP class into inline CSS styles?

While exploring MailChimp's css inliner at , I found myself curious if there are any available classes that can achieve the same result. It would be convenient to have this functionality directly in my email code without relying on MailChimp. I am es ...

Is there a method to exclude children objects from spring animations during application?

Is it possible to create a fading in and out effect for a div (for example, to cycle through different backgrounds) while keeping its children (such as text) visible at full opacity at all times? {transitions((style, <animated.div class={ bg[i] + ...

Navigate through FAQ items with sliders using Owl Carousel 2 - Easily switch between different chapters

Exploring the creation of a FAQ section with individual carousels for each item. My primary objective is for the carousel to transition to the next chapter when advancing beyond the last slide (backwards navigation would be a future enhancement). I'v ...

Persistent hover effect for collapsible accordion panels when closing them

My simple accordion features a functionality where a class of .open is added to the title + content group when you open a panel for styling purposes. Everything works smoothly, but I've noticed on my phone that after clicking to close a panel, the hov ...

Material UI Card shadow effect getting cropped

Currently experiencing an uncommon issue while using Material UI's Card component - the box-shadow is cut off on the top and bottom sides. Any suggestions on how to resolve this problem? Check out my code below: import React, { Component } from & ...

CSS Transform animation does not work when a class is added programmatically, although it functions properly when toggling the class in Chrome

Attempting to create an animation for the transform of a div. Below is the code with transition and transform properties in Safari: #mydiv{ transition: all 2.3s cubic-bezier(1, 0, 0, 1); transform: scale(0.5); background:white; padding:30 ...

Updating the CSS class for a particular text segment enclosed in a <p> or <span> element

My <p> tag is set to contain several lines of text with a specific CSS class, but I am looking to modify the text format within certain parts of the paragraph. In the past, I would achieve this using the <font> tag, however it seems that HTML5 ...

Elegant Border Separator

I'm attempting to achieve the design below (with a 1 pixel gap on each end): ...

Tips for automatically collapsing the Bootstrap 4 Sidebar on smaller devices

I am currently working on some code and have successfully hidden the sidebar using a collapse button. However, I am looking to make it collapse only for small devices, similar to how the bootstrap navbar functions. <link href="https://stackpath.boots ...

Struggling with the alignment of pictures inside a container

I utilized the Instafeed.js library to fetch the three most recent images from an Instagram account. These images are loaded into a specific div and I successfully customized their styling according to my requirements. However, the current setup is quite s ...

What is the best way to embed sections of one HTML page into another page?

Is there a method I can use to embed sections of one webpage within another webpage? The dilemma arises from the fact that the second page has a distinct style compared to my main page. Is it feasible to apply the alternate style solely to specific content ...

Achieving True Nested Divs: Making Children Truly Inside

I want to create nested divs for positioning children with top and left properties, allowing them to overlap each other: https://jsfiddle.net/e0cpuarv/ .boo { position: absolute; left: 10px; top: 10px; width: 100px ...