Use Nth-Child as CSS Variable

How to pass a CSS variable correctly in nth-child?

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>

Is there a way to use the n value in :nth-child(n)?

CSS doesn't have support for variables. You could use Less/SASS loops and define it for n up to some value, but that would output almost the same CSS multiple times. Here is Codepen example.

SCSS code to support up to 10 cards:

$n: 10;

@for $i from 1 through $n {
.card:nth-child(#{$i}) {
position: absolute;
left: 10px * $i;
top: 10px * $i;
}
}

But are you sure your approach is correct? Maybe you want to take a step back and look for a different approach. Because this still doesn't scale dynamically, you'll have to predict or limit n to some value. If you were to pick large n, it would result in a big CSS file, which equals longer load times.

Use nth-child value as a SASS variable

I don't think there's a way to do exactly that. But you can use @for directive to loop through a known number of elements:

$elements: 15;
@for $i from 0 to $elements {
div:nth-child(#{$i + 1}) {
background: rgb($i, $i, $i);
}
}


Related Topics



Leave a reply



Submit