Home > database >  How to pass a CSS variable correctly in nth-child
How to pass a CSS variable correctly in nth-child

Time:03-25

Goal: Successfully pass a variable as a parameter to nth-child. In the example below, the third line should turn green.

Problem: Currently the parameter is ignored as a variable.

Question: Is this possible at all? If yes, what do I have to change?

Example Code:

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

CodePudding user response:

The only place where you can use CSS custom properties (which are not "variables"!) is in declarations, after the :. This also means that unfortunately you cannot use these custom properties in selectors, or in media queries.

That is also the reason why people really should stop calling them CSS "variables".

You can, however, manipulate styles using 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>

CodePudding user response:

You can't do that with pure CSS, but you can try to write a JS function to do so.

This function:

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

Will get you '3' as described in your :root{}

Now, since you can't put js in your css, you have to do all of this in your HTML file. So your job is to wrap an html style tag around the variable that you get with 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'); //get your variable, in this case '3'

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

<div id="custom-container"> <!-- Mark your div container with and ID -->
  <p>a</p>
  <p>b</p>
  <p>c</p>
</div>

  •  Tags:  
  • css
  • Related